Home > Backend Development > C++ > 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
Release: 2023-09-03 14:53:07
forward
937 people have browsed it

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

Output

file exists
Copy after login

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";
   }
}
Copy after login

Output

file doesn&#39;t exist
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template