Eth*_*xxx -1 c++ fstream file ifstream
我想检查文件是否存在并尝试使用以下函数
#include <fstream>
bool DoesFileExist(const std::string& filename) {
std::ifstream ifile(filename.c_str());
return (bool)ifile;
}
Run Code Online (Sandbox Code Playgroud)
但是,它似乎没有正常工作,因为而不是检查存在是否创建了文件!这有什么问题?
请注意,我被迫使用C++ 98标准,不能使用#include <sys/stat.h>或#include <unistd.h>在此处接受的答案中建议.
您可以使用这些函数之一来查看文件是否存在
bool DoesFileExist (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
Run Code Online (Sandbox Code Playgroud)
要么
bool DoesFileExist (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
要么
bool DoesFileExist (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
Run Code Online (Sandbox Code Playgroud)
要么
bool DoesFileExist (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7634 次 |
| 最近记录: |