如何使用 fstream::open() 检查 C++ 中的文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25225948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:17:08  来源:igfitidea点击:

How to check if a file exists in C++ with fstream::open()

c++

提问by Mostafa Talebi

I'm using fstream library to work with files. Basically, I need to know if a certain file exists or not. In c++ documentation online, about open(), it reads:

我正在使用 fstream 库来处理文件。基本上,我需要知道某个文件是否存在。在 C++ 在线文档中,关于 open(),它是这样写的:

Return Value

none

If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).

返回值

没有任何

如果函数无法打开文件,则为流设置 failbit 状态标志(如果使用成员异常注册该状态标志,则可能会抛出 ios_base::failure )。

It says not return value is specified. But in case of failure, a flag is set. My question is that, I should I then access that flag, or to better ask, how should I see if open()is successful or not.

它说没有指定返回值。但是在失败的情况下,会设置一个标志。我的问题是,我应该然后访问该标志,或者更好地问,我应该如何查看是否open()成功。

I have this code so far:

到目前为止我有这个代码:

int Log::add()
{
    fstream fileStream;

    fileStream.open("logs.txt");
}

回答by Brian

It says it sets the failbit if the file couldn't be opened. So you can check for that bit:

它说如果无法打开文件,它会设置故障位。所以你可以检查那个位:

fileStream.open("logs.txt");
if (fileStream.fail()) {
    // file could not be opened
}

Actually, just if (fileStream)would work here as well, since ios(a base class of ifstream, ofstream, and fstream) has a conversion operator to bool.

其实,只是if (fileStream)会在这里工作为好,因为ios(基类的ifstreamofstreamfstream)具有转换运营商bool

Don't worry about the failure exception. You can request exceptions to be thrown on failure by calling ios::exceptionsbut by default exceptions are not thrown on failure.

不要担心失败异常。您可以通过调用请求在失败时抛出异常,ios::exceptions但默认情况下不会在失败时抛出异常。

Note that this doesn't tell you whythe file couldn't be opened. It could be that the file didn't exist, that a directory in the path didn't exist, you don't have permission to open the file, your program has reached the limit on the number of files it can open, and so on. There is no portable way to determine the reason.

请注意,这不会告诉您无法打开文件的原因。可能是文件不存在,路径中的目录不存在,您没有打开文件的权限,您的程序已达到可以打开的文件数限制,等等在。没有可移植的方法来确定原因。

回答by Non-maskable Interrupt

Note that there are difference between "File exist" and "File can be opened".

请注意,“文件存在”和“文件可以打开”之间存在差异。

To check if file exist (and you indeed do not need to open/read/write the file), use fstator its c++ counterpart - you don't need any permission to query the info.

要检查文件是否存在(并且您确实不需要打开/读取/写入文件),请使用fstat或它的 C++ 副本 - 您不需要任何权限来查询信息。

Note that if you want to check file exist before open it, you are doing it wrong. Condition may have changed between your checking and the actual attempt to open the file. In general, you just directly open the file with the open/creation options without previously checking.

请注意,如果您想在打开文件之前检查文件是否存在,那么您就做错了。在您检查和实际尝试打开文件之间,情况可能已发生变化。通常,您只需使用打开/创建选项直接打开文件,无需事先检查。

回答by Jayhello

There are two methods is_open, fail, for example:

有两种方法is_openfail例如:

string path = "not_exists.txt";
ifstream fin(path);

if(fin.is_open()){
    cout<<"file is open"<<endl;
} else{
    cout<<"file isn't open"<<endl;
}

if(fin.fail()){
    cout<<"file open fail"<<endl;
} else{
    cout<<"file open success"<<endl;
}

output as below:

输出如下:

enter image description here

在此处输入图片说明

enter image description here

在此处输入图片说明

See: http://www.cplusplus.com/reference/fstream/ifstream/for reference.

请参阅:http: //www.cplusplus.com/reference/fstream/ifstream/以供参考。

回答by Amit G.

Your method doesn't check for existence, but rather accessibility. It is possible to check existence like this:

您的方法不检查是否存在,而是检查可访问性。可以像这样检查存在:

inline bool exists (const std::string& filename) {
  struct stat buffer;   
  return (stat (filename.c_str(), &buffer) == 0); 
}
  • Using this needs to remember to #include <sys/stat.h>.
  • 使用这个需要记住#include <sys/stat.h>

-

——

In C++14 it is possible to use this:

在 C++14 中可以使用这个:

#include <experimental/filesystem>

bool exist = std::experimental::filesystem::exists(filename);

& in C++17: (reference)

& 在 C++17 中:(参考

#include <filesystem>

bool exist = std::filesystem::exists(filename);