我正在使用 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).
它说没有指定返回值。但如果失败,则会设置一个标志。我的问题是,我应该访问该标志,或者更好地问,我应该如何查看 open()
是否成功。
到目前为止我有这段代码:
int Log::add()
{
fstream fileStream;
fileStream.open("logs.txt");
}
最佳答案
它表示如果文件无法打开它会设置故障位。所以你可以检查那个位:
fileStream.open("logs.txt");
if (fileStream.fail()) {
// file could not be opened
}
实际上,if (fileStream)
也可以在这里工作,因为 ios
(ifstream
的基类,ofstream
和 fstream
) 有一个到 bool
的转换运算符。
不用担心失败异常。您可以通过调用 ios::exceptions
请求在失败时抛出异常,但默认情况下不会在失败时抛出异常。
请注意,这并没有告诉您为什么文件无法打开。可能是文件不存在,路径中的目录不存在,你没有权限打开文件,你的程序已经达到了它可以打开的文件数量的限制,等等在。没有可移植的方法来确定原因。
关于c++ - 如何使用 fstream::open() 检查文件是否存在于 C++ 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225948/