检查文件是否存在的唯一方法是尝试打开文件以进行读取或写入。
这是一个例子-
#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
#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