I am trying to read all file names present in a particular directory. I have made a program in C++ but this only prints the files directly in this directory. I want all the files which are also present in the subdirectory.
I have written a program in c++ which prints the file names in a directory but I want all file names in subdirectory also.
#include <stdio.h>
#include <windows.h>
#include <bits/stdc++.h>
#include <dirent.h>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#endif
#ifdef WIN32
#define stat _stat
#endif
int main ()
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\test")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
}
Actual result:1.Printing file names which are directly in the directory and printing the subdirectory name.
Expected: I want instead of printing subdirectory name the program should print the names of files in that subdirectory.
If you have C++17 available, use recursive_directory_iterator. If not, you could use dirent.h-functions. Consider, for example, the following generic traverseFiles-function, which passes each file found then to a function that handles the file detected:
#include <iostream>
#include <dirent.h>
#include <string>
void traverseFiles(const std::string &path, std::function<void(const std::string &)> cb) {
if (auto dir = opendir(path.c_str())) {
while (auto f = readdir(dir)) {
if (f->d_name[0] == '.') continue;
if (f->d_type == DT_DIR)
traverseFiles(path + f->d_name + "/", cb);
if (f->d_type == DT_REG)
cb(path + f->d_name);
}
closedir(dir);
}
}
void fileDetected(const std::string &f) {
std::cout << "file:" << f << std::endl;
}
int main() {
traverseFiles("c:/somestartdir", &fileDetected);
}
Using C++17 recursive_directory_iterator:
#include <filesystem>
void ls_recursive(const std::filesystem::path& path) {
for(const auto& p: std::filesystem::recursive_directory_iterator(path)) {
std::cout << p.path() << '\n';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With