Home > Article > Backend Development > Using standard C/C++, what is the best way to check if a file exists?
The only way to check if a file exists is to try to open it for reading or writing.
Here is an example:
#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
The above is the detailed content of Using standard C/C++, what is the best way to check if a file exists?. For more information, please follow other related articles on the PHP Chinese website!