为什么输出“错误打开文件"?如果我在此代码中注释了注释行,则不会显示? [英] why the output "Error opening file" does not display if i comment the commented lines in this code?

查看:50
本文介绍了为什么输出“错误打开文件"?如果我在此代码中注释了注释行,则不会显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,当我注释这两行时,输出错误打开文件"不会显示在屏幕上,但是当我不注释下面这两行时,程序将显示输出错误打开文件",为什么是吗?

in this code when i comment these two lines the output "Error opening file" does not display to the screen but when i do not comment these two below commented lines the output "Error opening file" is displayed by the program , why it is?

int main()
{
    fstream f;
    //f.open("D:\\Test",ios::in);
    //f.close();
    
    if(!f)
          cout<<"Error opening file";
          
    getch();
    return 0;
}

推荐答案

我建​​议您看看^ ]

您正在打开和关闭文件.通过关闭,可以取消关联fstream的文件.

来自网站的报价:
一旦关闭,则可以使用同一文件流对象打开另一个文件
[/quote]

另一方面,打开文件并不一定意味着创建文件.
I recommend you to have a look here[^]

You are opening and closing the file. By closing you disassociate the file of the fstream.

quote from the site:
Once closed, the same file stream object may be used to open another file
[/quote]

On the other hand... open file does not necessary mean create file.


看起来打开操作失败.因此,failbit标志将在fstream对象中设置,并且在!f表达式中进行了测试.

当注释掉这两行时,您将拥有一个未设置故障位的全新fstream对象-尚未发生错误.

因此,我的猜测是您没有名为"D:\\ Test"的文件.也许您有一个文件"Test.< something>".在驱动器D的根目录中有另一个文件类型:?
Looks like the open operation fails. Hence, the failbit flag gets set in the fstream object and that is what''s tested in the !f expression.

When you comment the two lines out you have a brand new fstream object which has the failbit not set -- no error has occurred yet.

So my guess would be that you don''t have a file named "D:\\Test". Perhaps you have a file "Test.<something>" with another file type in the root directory of drive D:?


这篇关于为什么输出“错误打开文件"?如果我在此代码中注释了注释行,则不会显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆