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


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

Updated on: 30-Jul-2019

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements