Check if File Exists

Checking if a File Exists in C++

IntermediateTopic: File Handling Programs
Back

C++ Check if File Exists Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <fstream>
#include <filesystem>
using namespace std;
using namespace filesystem;

bool fileExists(const string& filename) {
    ifstream file(filename);
    return file.good();
}

int main() {
    string filename = "data.txt";
    
    // Method 1: Using ifstream
    if (fileExists(filename)) {
        cout << "File '" << filename << "' exists (Method 1)" << endl;
    } else {
        cout << "File '" << filename << "' does not exist (Method 1)" << endl;
    }
    
    // Method 2: Using filesystem (C++17)
    if (exists(filename)) {
        cout << "File '" << filename << "' exists (Method 2)" << endl;
        
        // Get file size
        cout << "File size: " << file_size(filename) << " bytes" << endl;
    } else {
        cout << "File '" << filename << "' does not exist (Method 2)" << endl;
    }
    
    // Check multiple files
    string files[] = {"data.txt", "test.txt", "output.txt"};
    
    cout << "\nChecking multiple files:" << endl;
    for (const string& file : files) {
        if (exists(file)) {
            cout << file << " - EXISTS (" << file_size(file) << " bytes)" << endl;
        } else {
            cout << file << " - NOT FOUND" << endl;
        }
    }
    
    return 0;
}
Output
File 'data.txt' exists (Method 1)
File 'data.txt' exists (Method 2)
File size: 156 bytes

Checking multiple files:
data.txt - EXISTS (156 bytes)
test.txt - NOT FOUND
output.txt - NOT FOUND

Understanding Check if File Exists

To check if a file exists: 1) Try opening with ifstream and check good(), 2) Use filesystem::exists() (C++17). The filesystem library also provides file_size(), is_regular_file(), is_directory(), etc. Always handle the case where file doesn't exist to avoid errors.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents