Home  >  Article  >  Backend Development  >  Using standard C/C++, what is the best way to check if a file exists?

Using standard C/C++, what is the best way to check if a file exists?

WBOY
WBOYforward
2023-09-03 14:53:07879browse

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:

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&#39;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&#39;t exist";
   }
}

Output

file doesn&#39;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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete