Check if File Exists in C++

Checking if a File Exists in C++.

IntermediateFile Handling ProgramsExample 5 of 6
check-if-file-exists.cpp
1#include <iostream>
2#include <fstream>
3#include <filesystem>
4using namespace std;
5using namespace filesystem;
6
7bool fileExists(const string& filename) {
8 ifstream file(filename);
9 return file.good();
10}
11
12int main() {
13 string filename = "data.txt";
14
15 // Method 1: Using ifstream
16 if (fileExists(filename)) {
17 cout << "File '" << filename << "' exists (Method 1)" << endl;
18 } else {
19 cout << "File '" << filename << "' does not exist (Method 1)" << endl;
20 }
21
22 // Method 2: Using filesystem (C++17)
23 if (exists(filename)) {
24 cout << "File '" << filename << "' exists (Method 2)" << endl;
25
26 // Get file size
27 cout << "File size: " << file_size(filename) << " bytes" << endl;
28 } else {
29 cout << "File '" << filename << "' does not exist (Method 2)" << endl;
30 }
31
32 // Check multiple files
33 string files[] = {"data.txt", "test.txt", "output.txt"};
34
35 cout << "\nChecking multiple files:" << endl;
36 for (const string& file : files) {
37 if (exists(file)) {
38 cout << file << " - EXISTS (" << file_size(file) << " bytes)" << endl;
39 } else {
40 cout << file << " - NOT FOUND" << endl;
41 }
42 }
43
44 return 0;
45}

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

What's going on

The program demonstrates file existence checking:

Method 1: Using ifstream and good()
Method 2: Using filesystem::exists() (C++17)
Getting file size
Checking multiple files

File existence checking prevents errors and enables safe file operations.

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <fstream>
Provides file stream classes (ifstream).
3.#include <filesystem>
Provides filesystem operations (C++17).

Understanding File Existence

Existence Check Concept

:

Verify file exists before operations
Prevents errors from missing files
Enables conditional file handling
Multiple methods available

Why Check?

Avoid read errors
Prevent overwrite accidents
Handle missing files gracefully
Provide user feedback

Method 1: Using ifstream

Function

:

bool fileExists(const string& filename) {

ifstream file(filename);

}

1return file.good();

How it works

:

Try opening file with ifstream
good() returns true if file opened
Works on older C++ standards
Simple and portable

Usage

:

if (fileExists("data.txt")) {

}

1// File exists

Method 2: Using filesystem (C++17)

Using exists()

:

if (exists(filename)) {

}

1// File exists

How it works

:

filesystem::exists() checks existence
Modern C++17 approach
More features available
Recommended for C++17+

Getting File Information

File Size

:

file_size(filename) // Returns size in bytes

File Type

:

is_regular_file(filename) // True if regular file

is_directory(filename) // True if directory

How it works

:

filesystem provides file information
Size, type, permissions
More detailed than basic check
Useful for file management

Checking Multiple Files

Loop Through Files

:

string files[] = {"data.txt", "test.txt", "output.txt"};

for (const string& file : files) {

if (exists(file)) {

}

}

1cout << file << " - EXISTS" << endl;

How it works

:

Check multiple files efficiently
Batch file verification
Useful for file management
Process files conditionally

When to Use Each Method

ifstream Method

:

Older C++ standards
Simple existence check
Portable across systems
Basic file operations

filesystem Method

:

C++17 or later
More features (size, type)
Modern approach
Recommended for new code

Important Considerations

Error Handling

:

Always check before operations
Handle missing files gracefully
Provide user feedback
Avoid crashes from missing files

File Permissions

:

File may exist but not readable
Check permissions separately
Handle access errors
Provide appropriate messages

Path Handling

:

Relative vs absolute paths
Path separators (/ or \)
Current directory matters
Verify path correctness

return 0;

This ends the program successfully.