#include using namespace std;
// 方法一:使用fstream的is_open()函数判断文件是否存在 ifstream fin; fin.open(“filename”); if( fin.is_open() ) cout << “File exists” << endl; else cout << “Error! File does not exist” << endl; fin.close();
// 方法二:使用ifstream构造函数判断文件是否存在 ifstream fin(“filename”); if( fin ) cout << “File exists” << endl; else cout << “Error! File does not exist” << endl;
C++ 文件是否存在可以使用c++内置的 < fstream > 头文件来判断:
#include <fstream>
using namespace std;
int main(){
ifstream file("filename.txt"); //filename.txt 是你要检查的文件
if(file){ //如果文件存在,返回true
cout << "File exist." << endl;
}
else { //如果文件不存在,返回false
cout << "File does not exist." << endl;
}
return 0;
}
若要判断文件是否存在,可以使用 Linux 中的 access() 函数,其原型为:
int access(const char *pathname, int mode);
其中pathname 是指定文件的路径,mode可以是F_OK,表示判断文件是否存在;mode也可以是执行权的判断方式,比如R_OK,表示有读取文件的权限;还有W_OK、X_OK等权限判断方式,具体的可以查看access的Linux的man文档;
C++ 可以使用 <sys/stat.h> 头文件中的stat()函数进行文件的判断,其原型为:
int stat(const char *file_name, struct stat *buf);
参数file_name表示文件名,buf参数用于存储该文件信息,如果文件存在,该函数会返回一个零值;其中可以使用buf->st_mode == S_IFREG 判断,若结果为true,则说明这是一个普通文件;另外buf->st_mode == NULL 也可以判断文件是否存在,若返回值为true,则表示文件不存在;
#include <string>
#include <fstream>
bool FileExists(const std::string& FileName)
{
std::ifstream file(FileName);
return file.good();
}
#include <iostream>
#include<string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cout<<"请输入要判断的文件路径:";
cin>>fileName;
ifstream file(fileName);
if (file)
cout<<"文件存在"<<endl;
else
cout<<"文件不存在"<<endl;
return 0;
}