วิธีเดียวที่จะตรวจสอบว่ามีไฟล์อยู่หรือไม่คือพยายามเปิดไฟล์เพื่ออ่านหรือเขียน
นี่คือตัวอย่าง −
ใน 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