Cách duy nhất để kiểm tra xem tệp có tồn tại hay không là cố gắng mở tệp để đọc hoặc ghi.
Đây là một ví dụ -
Trong C
Ví dụ
#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");
}
} Đầu ra
Tệpfile exists
Trong C ++
Ví dụ
#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";
}
} Đầu ra
file doesn't exist