使用標準 C/C++ 檢查檔案是否存在最好的方式
檢查檔案是否存在,唯一的方法是嘗試開啟該檔案進行讀取或寫入。
以下是示例 −
在 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
廣告