There is a folder with text documents in it, for example: a.txt, b.txt. How to display the names of these files?

include <iostream> using namespace std; int main(int argc, const char * argv[]) { ... cin.get(); } 

    3 answers 3

    In modern C ++, something like this:

     #include <iostream> #ifdef __cpp_lib_filesystem #include <filesystem> namespace fs = std::filesystem; #else #include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif int main(int argc, const char *argv[]) { if (argc < 2) { std::cerr << "provide an argument"; return 1; } const auto dir = argv[1]; for (const auto &f : fs::directory_iterator(dir)) { std::cout << f << std::endl; } return 0; } 

    Compile with -std=c++17 and most likely -lstdc++fs .

    See also http://en.cppreference.com/w/cpp/filesystem/directory_iterator .

    • c ++ 17 too new language, is there something like that on the old one? - Vengeance Of the ghosts
    • -std = gnu ++ 17 is used by me, I'm not sure, but it seems like -std = c ++ 17 may not work for now - goldstar_labs
    • one
      @goldstar_labs I have GCC 5.4.0, std=c++17 works if I additionally connect libstdc++fs . - Ainar-G
    • @ Ainar-G, need to be updated) thanks for the info - goldstar_labs

    If without C ++ 17, it works like this:

     #include <iostream> #include <dirent.h> int main() { if (argc < 2) { std::cerr << "Provide an argument"; return 1; } DIR *dir = opendir(argv[1]); if (!dir) { std::cerr << "Could not open directory"; return 2; } dirent *entry; while ((entry = readdir(dir)) != nullptr) { std::cout << entry->d_name << std::endl; } } 

      Found an option through the terminal:

       system("ls | tee text.txt"); 

      Then we output the data from this file using fstream.

      • Sorry, but the already proposed solutions really did not help? If not, why not? - 0xdb
      • I did not say that they did not help, I just offered another option, perhaps it is not quite correct, but working and suitable for this task. - Vengeance Of the ghosts
      • If no answer is marked as accepted, then none of them helped. And giving the answer, you just confirmed. - 0xdb