- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements