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.
1#include <iostream>2#include <fstream>3#include <filesystem>4using namespace std;5using namespace filesystem;67bool fileExists(const string& filename) {8 ifstream file(filename);9 return file.good();10}1112int main() {13 string filename = "data.txt";1415 // Method 1: Using ifstream16 if (fileExists(filename)) {17 cout << "File '" << filename << "' exists (Method 1)" << endl;18 } else {19 cout << "File '" << filename << "' does not exist (Method 1)" << endl;20 }2122 // Method 2: Using filesystem (C++17)23 if (exists(filename)) {24 cout << "File '" << filename << "' exists (Method 2)" << endl;2526 // Get file size27 cout << "File size: " << file_size(filename) << " bytes" << endl;28 } else {29 cout << "File '" << filename << "' does not exist (Method 2)" << endl;30 }3132 // Check multiple files33 string files[] = {"data.txt", "test.txt", "output.txt"};3435 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 }4344 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
Method 1: open data.txt with ifstream and return good().
- 2
Method 2: filesystem::exists and file_size.
- 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:
Why Check?
Method 1: Using ifstream
Function:
bool fileExists(const string& filename) {
ifstream file(filename);
return file.good();
}
What happens here:
Usage:
if (fileExists("data.txt")) {
// File exists
}
Method 2: Using filesystem (C++17)
Using exists():
if (exists(filename)) {
// File exists
}
What happens here:
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:
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:
When to Use Each Method
ifstream Method:
filesystem Method:
Important Considerations
Error Handling:
File Permissions:
Path Handling:
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;