Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Check if File Exists in C++

Check if a file exists in C++ two ways: opening it with ifstream, and std::filesystem::exists in C++17, plus file_size to get the file size in bytes.

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}

Sample Output

File size: 146 bytes

97 bytes from file-write plus 49 from file-append.

test.txt - NOT FOUND

No such file in the working directory.

In this one

  • How to test a file with ifstream::good()
  • How filesystem::exists checks without opening
  • How to get a file size with file_size
  • Why check-then-act can be unreliable

How it works

  1. 1

    Method 1: open data.txt with ifstream and return good().

  2. 2

    Method 2: filesystem::exists and file_size.

  3. 3

    Loop over three names and print EXISTS with size or NOT FOUND.

Edge cases

Compiling as C++14

Build with -std=c++14.

<filesystem> and std::filesystem are C++17 features, so the build fails with an error like "expected namespace name". Use -std=c++17.

file_size on a missing file

Call file_size("test.txt") without checking.

It throws filesystem_error. That is why the loop checks exists first.

Path is a folder

Create a folder named data.txt.

exists returns true, but file_size throws because a folder has no file size. Use is_regular_file to be sure it is a file.

What's going on

Before opening or deleting a file, you often want to know whether it is there. This program shows two ways and then checks several names. It needs C++17 for <filesystem>; compile with -std=c++17 or newer.

Method 1 is the old portable trick. fileExists opens the file with ifstream and returns file.good(). If the open succeeded, the stream is good. This answers "can I read it?", which is not quite "does it exist?": a file you lack permission to read, or a folder with that name, can fail the check even though something is there.

Method 2 uses std::filesystem::exists(filename), which asks the operating system directly and does not open anything. The line using namespace filesystem; lets the code write exists and file_size without the std::filesystem:: prefix. (It works because using namespace std; came first; the full name is std::filesystem.)

file_size(filename) returns the size in bytes. The sample shows 146 bytes, which is what data.txt holds after file-write and then file-append run once each on Linux or macOS: 97 bytes of original text plus 49 appended. On Windows, text mode writes each newline as two bytes, so the number is larger.

The loop checks data.txt, test.txt, and output.txt. For each one that exists it prints the size; the others print NOT FOUND.

One caution: a file can appear or disappear between the check and your next action. For anything important, try the operation and handle the failure instead of relying only on a check done earlier.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <fstream> is there because it provides file stream classes (ifstream). <filesystem> is there because it provides filesystem operations (C++17). Leave one out and the compiler stops at the first name it does not recognize.

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);

return file.good();

}

What happens here:

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

Usage:

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

// File exists

}

Method 2: Using filesystem (C++17)

Using exists():

if (exists(filename)) {

// File exists

}

What happens here:

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

What happens here:

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)) {

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

}

}

What happens here:

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;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does filesystem::exists do that the ifstream check does not?

Pick an answer to check it.

Question 2

What does file_size throw for a missing file?

Pick an answer to check it.

Questions people ask

Which method should I use?

filesystem::exists in C++17 and later. Use the ifstream check only on older compilers.

Do I need to link anything?

Modern GCC and Clang do not. GCC 8 needed -lstdc++fs.

How do I list files in a folder?

for (auto& e : directory_iterator(".")) cout << e.path() << endl;