Один из способов - сделать stat()
и проверить на errno
.
пример кода будет выглядеть выглядеть так:
#include <sys/stat.h>
using namespace std;
// some lines of code...
int fileExist(const string &filePath) {
struct stat statBuff;
if (stat(filePath.c_str(), &statBuff) < 0) {
if (errno == ENOENT) return -ENOENT;
}
else
// do stuff with file
}
Это работает независимо от потока. Если вы все еще предпочитаете проверять, используя ofstream
, просто проверьте, используя is_open()
.
Пример:
ofstream fp.open("<path-to-file>", ofstream::out);
if (!fp.is_open())
return false;
else
// do stuff with file
Надеется, что это помогает. Спасибо!
Возможные дублирующие вопросы: http://stackoverflow.com/questions/1383617/how-to-check-if-a-file-exists-and-is-readable-in-c, http://stackoverflow.com/questions/574285/check-exist-of-a-txt-file-with-c-code, http://stackoverflow.com/questions/268023/whats-the-best-way-to-check-if-a -file-exists-in-c-cross-platform – 2010-11-30 17:18:49
Добавить дубликат: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c -c11-c – zhangxaochen 2016-04-04 04:35:55