C++基础:判断文件是否存在的方法
使用以下几种函数判断文件是否存在
#include <fstream>--> 使用ifstream打开文件流,成功则存在,失败则不存在;#include <stdio.h>--> 以fopen读方式打开文件,成功则存在,否则不存在;#include <unistd.h>--> 使用access函数获取文件状态,成功则存在,否则不存在#include <sys/stat.h>--> 使用stat函数获取文件状态,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
bool isFileExists_ifstream(string& name) {
ifstream f(name.c_str());
return f.good();
}
bool isFileExists_fopen(string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
bool isFileExists_access(string& name) {
return (access(name.c_str(), F_OK ) != -1 );
}
bool isFileExists_stat(string& name) {
struct stat buffer;
return (stat(name.c_str(), &buffer) == 0);
}
参考衔接2
若你对人工智能(CV/NLP)、C++/python编程、互联网就业及发展有兴趣,欢迎点赞关注和收藏。谢谢鼓励!!!
C++相关知识:
Anxjing.AI:C++ this_thread::sleep_forzhuanlan.zhihu.com





















本文介绍了使用C++通过四种不同的方法来判断文件是否存在:利用ifstream流、fopen函数、access函数以及stat函数。这些方法涵盖了从标准输入输出到系统调用的不同层面。

1万+

被折叠的 条评论
为什么被折叠?



