C++ Program to Get the List of Files in a Directory
Last Updated :
06 Feb, 2023
Getting the list of files in a directory is one of the most common operations performed by the Filesystem of an OS. The file explorer application in most operating systems performs the same operation in the background. In this article, you will learn how to get the list of files in a directory using C++.
Two methods can be used to Get the List of Files in a Directory:
- Using the system function - ( functions in C++ )
- Using the directory_iterator - ( Invoking directory traversing commands from the operating system's command interpreter )
1. Getting the list of files using the system function
The list of files in a directory could be obtained by calling the system function and sending an argument to dir /a-d for Windows OS (or ls -p | grep -v / in Linux OS). The help page of the command is as follows:
Directory displayed using cmd
A Windows machine would be used for demonstration, and the list of files in the following directory would be obtained.
File explorer to view directories
Code:
C++
// C++ Program to Getting
// the list of files using
// the system function
#include <bits/stdc++.h>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
// This variable contains the path to the directory
// The path should be given inside double quotes
// Therefore, escaped the enclosing quotes using
// backslash
string path(
"\"C:\\Users\\Sauleyayan\\Desktop\\New folder\"");
// The command which would do the file listing
// A space is added at the end of the command
// intentionally to make space for the path
string command("dir /a-d ");
// The path is appended after the command string
command.append(path);
// The string is converted to const char * as system
// function requires
const char* final_command = command.c_str();
// Sending the final command as the argument to the
// system function
system(final_command);
return 0;
}
Output:
Output of Program
Explanation: Firstly, the cstdlib header file is imported to allow the use of the system function. Then the directory's path on which the files are to be searched is assigned to the variable path. Then another variable named command is assigned the command to be run. After which, both variables are concatenated to produce the final command. Then another variable of type const char * is defined and assigned the value of the aforementioned concatenated string. Since the system function requires a const char * as an argument, this conversion was necessary. Then the char array (containing the command) is passed to the system function, which delivers the desired result.
2. Getting the list of files using the directory_iterator function
Getting the list of files within a directory could be done by using an iterator on the directory. Which will go through each element of the directory one by one. Then distinguishes whether the path belongs to a file or directory and, in the end, displays the valid ones.
The following code uses C++17 standard code.
Code:
C++
// C++ Program for Getting
// the list of files using
// the directory_iterator function
#include <filesystem>
#include <iostream>
#include <string>
#include <sys/stat.h>
namespace fs = std::filesystem;
int main()
{
// Path to the directory
std::string path
= "C:\\Users\\Sauleyayan\\Desktop\\New folder";
// This structure would distinguish a file from a
// directory
struct stat sb;
// Looping until all the items of the directory are
// exhausted
for (const auto& entry : fs::directory_iterator(path)) {
// Converting the path to const char * in the
// subsequent lines
std::filesystem::path outfilename = entry.path();
std::string outfilename_str = outfilename.string();
const char* path = outfilename_str.c_str();
// Testing whether the path points to a
// non-directory or not If it does, displays path
if (stat(path, &sb) == 0 && !(sb.st_mode & S_IFDIR))
std ::cout << path << std::endl;
}
}
Output:
Output of Program
Explanation: Firstly the header files filesystem and sys/stat.h were imported. Then a path to the directory is assigned to a variable. A structure template is initialized, which will be used to differentiate between a file and a directory. Then in a for loop, all the directory elements are iterated through. The first three statements in the for loop are just converting the path to the directory element from std::filesystem::path to const char * datatype. This is required as the stat function takes in an argument a character array, hence the requirement for this conversion. Then in an if the condition it is checked whether the path belongs to a directory or not. If it does not, then the path is displayed. Otherwise, it is ignored.
Similar Reads
Create Directory or Folder with C/C++ Program Problem: Write a C/C++ program to create a folder in a specific directory path. This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty director
2 min read
C++ Program to Create a Temporary File Here, we will see how to create a temporary file using a C++ program. Temporary file in C++ can be created using the tmpfile() method defined in the <cstdio> header file. The temporary file created has a unique auto-generated filename. The file created is opened in binary mode and has access m
2 min read
How to Check a File or Directory Exists in C++? 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 director
4 min read
C++ Program to Read and Print All Files From a Zip File In this article, we will explore how to create a C++ program to read and print all files contained within a zip archive. What are zip files? Zip files are a popular way to compress and store multiple files in a single container. They use an algorithm to decrease the size of the data they store. They
3 min read
C++ Program to Read Content From One File and Write it Into Another File Here, we will see how to read contents from one file and write it to another file using a C++ program. Let us consider two files file1.txt and file2.txt. We are going to read the content of file.txt and write it in file2.txt Contents of file1.txt: Welcome to GeeksForGeeks Approach: Create an input f
2 min read
How to Declare a List in C++? In C++, list is a data structure used to store elements sequentially in non-contiguous memory locations. This container implements doubly linked list which contains pointers to both previous and next elements in the sequence. In this article, we will learn how to declare a list in C++. Declare a Lis
2 min read
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 Read a File Line by Line in C++? In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we'll learn how to read a file line by line in C++. Read a File Line by Line in C++We can use the std::getline() function to read the input line by
2 min read
How to Read File into String in C++? In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to
2 min read
Error Handling During File Operations in C File operations are a common task in C programming, but they can encounter various errors that need to be handled gracefully. Proper error handling ensures that your program can handle unexpected situations, such as missing files or insufficient permissions, without crashing. In this article, we wil
5 min read