How to Check if File Exists in C++: Simple Methods
In C++, you can check if a file exists by using the
std::filesystem::exists() function from the <filesystem> header. Alternatively, you can try opening the file with std::ifstream and check if the stream is good.Syntax
The modern and recommended way to check if a file exists is using std::filesystem::exists(path). Here, path is a string or std::filesystem::path representing the file location.
- std::filesystem::exists(path): Returns
trueif the file or directory exists, otherwisefalse. path: The file path as a string orstd::filesystem::path.
Alternatively, you can use std::ifstream file(path) and check file.good() to see if the file can be opened (exists and accessible).
cpp
bool fileExists = std::filesystem::exists("filename.txt");Example
This example shows how to check if a file named example.txt exists using std::filesystem::exists. It prints a message based on the result.
cpp
#include <iostream> #include <filesystem> int main() { const std::string filename = "example.txt"; if (std::filesystem::exists(filename)) { std::cout << "File '" << filename << "' exists.\n"; } else { std::cout << "File '" << filename << "' does not exist.\n"; } return 0; }
Output
File 'example.txt' exists.
Common Pitfalls
- Not including the
<filesystem>header or compiling with C++17 or later causes errors. - Using
std::ifstreamto check existence can fail if the file is not readable. - Checking existence does not guarantee the file can be opened later due to permissions.
- Using deprecated or platform-specific functions instead of
std::filesystemis less portable.
cpp
#include <iostream> #include <fstream> int main() { const char* filename = "example.txt"; // Wrong: Only checks if file can be opened, not existence in all cases std::ifstream file(filename); if (file.good()) { std::cout << "File exists (checked by ifstream).\n"; } else { std::cout << "File does not exist or cannot be opened.\n"; } // Right: Use filesystem (C++17 and later) // #include <filesystem> // if (std::filesystem::exists(filename)) { ... } return 0; }
Quick Reference
Summary tips for checking file existence in C++:
- Use
std::filesystem::exists(path)for a clear and reliable check. - Make sure to compile with
-std=c++17or newer to use<filesystem>. - Opening a file with
std::ifstreamcan be a fallback but may not always be reliable. - Remember that existence does not guarantee access permissions.
Key Takeaways
Use std::filesystem::exists() from to check if a file exists in C++17 or later.
Always include and compile with C++17 or newer for this method.
Opening a file with std::ifstream can check existence but may fail if the file is unreadable.
File existence check does not guarantee you can open or write to the file.
Avoid older or platform-specific methods for better portability and clarity.