检查文件是否存在的唯一方法是尝试以读取或写入的方式打开文件。
下面是一个示例:
在C语言中
示例
'#include<stdio.h>
int main() {
/* try to open file to read */
FILE *file;
if (file = fopen("a.txt", "r")) {
fclose(file);
printf("file exists");
} else {
printf("file doesn't exist");
}
}
输出
'file exists
在 C++ 中
示例
'#include <fstream>
#include<iostream>
using namespace std;
int main() {
/* try to open file to read */
ifstream ifile;
ifile.open("b.txt");
if(ifile) {
cout<<"file exists";
} else {
cout<<"file doesn't exist";
}
}
输出
'file doesn't exist