检查在C++中的文件是否存在,而无需创建文件
问题描述:
我想检查文件是否存在,并试图使用下面的函数检查在C++中的文件是否存在,而无需创建文件
#include <fstream>
bool DoesFileExist(const std::string& filename) {
std::ifstream ifile(filename.c_str());
return (bool)ifile;
}
但是,它似乎并没有正常工作,因为而不是检查存在,一个文件被创建!这里有什么问题?
请注意,我被迫使用C++ 98标准,不能使用#include <sys/stat.h>
或#include <unistd.h>
作为接受的答案建议here.
答
您可以使用这些功能,看文件是否存在
bool DoesFileExist (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
或
bool DoesFileExist (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
或
bool DoesFileExist (const std::string& name) {
return (access(name.c_str(), F_OK) != -1);
}
或
bool DoesFileExist (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
+1
适合使用fopen ()'。不幸的是,'std :: ifstream'可以有效地创建一个文件。 –
如果可能的话,学习C++ 11; C + 98真的过时了。仔细阅读[std :: ifstream](http://en.cppreference.com/w/cpp/io/basic_ifstream)的文档。发布一些[MCVE](https://stackoverflow.com/help/mcve)。您显示的代码可能不像您所说的那样行为 –
[这个答案](https://stackoverflow.com/a/6297560/4143855)没有帮助吗? 'std :: fstream ifile(filename.c_str(),ios_base :: out | ios_base :: in);' – Tas
不可重复https://ideone.com/Z4c2EW –