Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all file names in a directory

Tags:

c++

file

windows

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.

like image 368
John Wick1 Avatar asked Oct 29 '25 13:10

John Wick1


2 Answers

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);
}
like image 80
Stephan Lechner Avatar answered Nov 01 '25 02:11

Stephan Lechner


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';
    }
}
like image 42
Leśny Rumcajs Avatar answered Nov 01 '25 03:11

Leśny Rumcajs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!