C++:检查文件是否存在
问题:
在 C++ 中你想检查给定文件是否存在,但你不能使用 stat(),因为你的代码需要跨平台工作。
解决方案
此解决方案 100% 可移植(stat() 不是,即使它被广泛支持),但注意它会打开文件,所以如果文件存在但运行程序的用户不允许访问它,可能会失败
fexists.cpp
#include <fstream>
bool fexists(const char *filename) {
std::ifstream ifile(filename);
return (bool)ifile;
}如果你有文件名作为 std::string 而不是 cstring,你可以使用此代码片段:
fexists_string.cpp
#include <fstream>
bool fexists(const std::string& filename) {
std::ifstream ifile(filename.c_str());
return (bool)ifile;
}如果你确定可以访问 stat(),我推荐使用 stat。有关如何执行此操作的示例,请参见此后续博客文章。
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow