The best way to check if a file exists using standard C/C++

CC++Server Side ProgrammingProgramming

The only way to check if a file exist is to try to open the file for reading or writing.

Here is an example −

In C

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");
   }
}

Output

file exists

In C++

Example

#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";
   }
}

Output

file doesn't exist
raja
Published on 18-Jun-2019 08:32:26
Advertisements