How to Check a File or Directory Exists in C++?
Last Updated :
28 Apr, 2025
Checking the presence of a directory or a file is one of the most common operations performed by a file system in an Operating System. Most programming languages offer some level of file system accessibility in form of library functions. In this article, you will learn how to test a file or directory that exists in C++.
Note: stat function present in the sys/stat.h header file would be used in the program. The function is not a part of the C++ standard library.
Checking/Testing the presence of a directory
stat is a pre-defined function present in the sys/stat.h header file. The function takes a path and a structure as arguments in which the metadata associated with the file/directory if present would be stored. The function returns the value of 0 if the path is a valid one. For demonstration we would be testing the presence of the following directory:
Example:
C++
// C++ Program to test presence of file/Directory
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main()
{
// Path to the directory
const char* dir = "C:/Users/apples";
// Structure which would store the metadata
struct stat sb;
// Calls the function with path as argument
// If the file/directory exists at the path returns 0
// If block executes if path exists
if (stat(dir, &sb) == 0)
cout << "The path is valid!";
else
cout << "The Path is invalid!";
return 0;
}
Output:
The path is valid!
Explanation: Firstly, the path to the directory is stored in the dir pointer variable. Then the empty structure is initialized with the format that is present in the stat header file. This would store the metadata. Then, inside the if condition where a call to the stat function is made. If the path is valid i.e. the file/directory exists, then the output would be 0, otherwise, it would be non-zero. Hence if the condition would be true if the path is valid, otherwise the else block would be executed, displaying The Path is invalid! message.
Checking/Testing the presence of a file
The aforementioned process could be used to identify the presence of a file inside a directory as well. With some minor changes to the prior code, the presence of files could also be tested. Therefore, in this example, the attempt to detect the following file would be made
Example:
C++
// C++ Program to test presence of file
#include <iostream>
#include <sys/stat.h>
using namespace std;
int main()
{
// Path to the directory
const char* file = "C:\Temp\4real.png";
// Structure which would store the metadata
struct stat sb;
// Calls the function with path as argument
// If the file/directory exists at the path returns 0
// If block executes if path exists
if (stat(file, &sb) == 0 && !(sb.st_mode & S_IFDIR))
cout << "The path is valid!";
else
cout << "The Path is invalid!";
return 0;
}
Output:
The path is valid!
Explanation: Firstly, the path to the file is stored in the file pointer variable. Then the empty structure is initialized with the format that is present in the stat header file. This would store the metadata. Then, inside the if condition where a call to the stat function is made. If the path is valid i.e. the file exists, then the output would be 0, otherwise, it would be non-zero. Then we check if the path is to a directory using the S_IFDIR flag. If it is then the path is valid but is of a directory, else it is a path to a file.
Note: The process for determining path to a file works on Windows and Linux Distributions.
Similar Reads
How to Get Current Directory in C++ The current working directory, also known as the present working directory, is the location on the file system where the executing program is located and operates from. When working with files and directories in C++, it is important to determine the current working directory to find the resource fil
2 min read
How to Delete a File in C++? C++ file handling allows us to manipulate external files from our C++ program. We can create, remove, and update files using file handling. In this article, we will learn how to remove a file in C++. Delete a File in C++ To remove a file in C++, we can use the remove() function defined inside the
2 min read
How to Open and Close a File in C++? In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++. Open and Close a File in C++ The fst
2 min read
How to Read a File Character by Character in C++? In C++, file handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk). In this article, we will learn how to read a file character by character in C++. Example: Input: "Geeks for Geeks"Output: G e e k s f o r G e e k sRead Te
2 min read
How to Check if a Deque is Empty in C++? In C++, a deque is a container provided by the STL library that is similar to a queue. However, unlike queues, it allows insertion and deletion from both ends. In this article, we will learn how to determine whether a deque is empty or not in C++. Example: Input: myDeque = {2, 4, 6 } Output: dq1 is
2 min read
How to Check If a Set Contains an Element in C++? In C++, the std::set container stores the unique elements in the sorted order. In this article, we will learn how to check if the set contains a given element or not.ExamplesInput: s = {1, 3, 5, 7, 9}, x = 5Output: Element foundExplanation: The element 5 is present in the set.Input: s = {10, 20, 30,
4 min read
How to Check if a String is Empty in C++? In C++, strings are the sequence of characters that are stored as std::string class objects. In this article, we will learn how to check if a string is empty in C++ Example Input: str1="Hello! Geek" ; str2="" Output: str1 is not empty str2 is emptyChecking if the String is Empty in C++To check for a
2 min read
How to Check if a Vector Contains a Given Element in C++? In C++, a vector is a dynamic array that provides a resizable and efficient way to store elements. Vectors store their elements in contiguous memory locations, similar to arrays, which allows for efficient access and iteration.In this article, we will learn the different methods to check whether the
3 min read
How to Check if a Map is Empty in C++? In C++, a map is an associative container that stores elements as key-value pairs and an empty map means it contains no elements. In this article, we will learn how to check if a map is empty or not in C++. Example: Input: map<int,string>mp1 = {{1, "Ram"}, {2, "Mohit"}};map<int,string> m
2 min read
How to Check if a Set is Empty in C++? In C++, a set is an associative container that stores unique elements in a sorted order. In this article, we'll explore different approaches to check if a set is empty in C++ STL. Check if a Set is Empty or Not in C++To check if a std::set is empty in C++, we can use the std::set::empty() function.
2 min read