Dunc Dunc - 1 month ago 18
C Question

Checking a file exists in C

I'm attempting to open a file in a C application. How do I check that a file exists before trying to read from it?

Answer

Try to open it:

FILE * file;
file = fopen("file_name", "r"));
if (file){
   //file exists and can be opened 
   //...
   // close file when you're done
   fclose(file);
}else{
   //file doesn't exists or cannot be opened (es. you don't have access permission )
}
Comments