简体   繁体   English

关于使用ifstream确定C ++中是否存在文件的问题

[英]Question about deciding whether a file exists in C++ using ifstream

I found a c++ code which uses ifstream to decide whether a file exists. 我找到了一个c ++代码,它使用ifstream来决定文件是否存在。 That section is, 那部分是,

if (!ifstream(trajectory_file_name_)) {
    cerr << "ERROR: The trajectory file:";
    cerr << "\033[1;34m";
    cerr << trajectory_file_name_;
    cerr << "\033[0m";
    cerr << " does not exist.";
    cerr << endl;
    exit(1);
}

what I have learned from the textbook (like "c++ primer plus") is something like, when judging whether a file exist via ifstream, 从教科书中学到的东西(比如“c ++ primer plus”)就像判断ifstream是否存在文件一样,

ifstream inFile(filename-);
if(!inFile.is_open())
{
  return;
}

I have searched many website but didn't find any information on the first one. 我搜索了很多网站,但没有找到第一个的任何信息。 So I wonder if anyone can give me some explanation on the usage of ifstream of the first one. 所以我想知道是否有人可以给我一些关于第一个ifstream的使用的解释。 Thanks! 谢谢!

This comes down to how streams convert to bool (or in this case it's due to operator! , but same principle). 这归结为如何转换为bool (或者在这种情况下,它是由于operator! ,但原理相同)。

It's designed so that, for short, you can check for openness ( and error flags ) like: 它的设计使得,简而言之,您可以检查开放性( 和错误标志 ),如:

std::ifstream ifs("path");
if (!ifs)
{
   // ...
}

(Failure to open sets the failbit ). (未能打开设置failbit )。

Your version just skips the declaration and does the same thing with a temporary. 你的版本只是跳过声明并用临时做同样的事情。

Note that there are other reasons a file may not be openable, eg permissions. 请注意,文件可能无法打开的其他原因,例如权限。 This is not a reliable way to check whether it exists and, even if it does, you have no way of guaranteeing that it will still exist in a moment when you try to do something with it. 这不是检查它是否存在的可靠方法,即使它确实存在,也无法保证它在您尝试使用它时仍然存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM