วิธีเดียวที่จะตรวจสอบว่าไฟล์มีอยู่จริงคือลองเปิดไฟล์เพื่ออ่านหรือเขียน
ตัวอย่าง:
ใน C
ตัวอย่าง
#include<stdio.h> int main() { 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() { ifstream ifile; ifile.open("b.txt"); if(ifile) { cout<<"file exists"; } else { cout<<"file doesn't exist"; } }ผลลัพธ์
file doesn't exist