0

I was trying to do this with the header <experimental/filesystem> but in c++17 it is deprectaed. I don't put the code here because i dont even sure what i was doing.

Basically, i want to see all txt files that are in the same directory as the executable, but we don't know the names of that txt files or how many txt files are. And of course, be able to read them.

  • 3
    I think made it to the standard in c++17, so it's no longer experimental. Try `#include ` – DeltA Jan 05 '21 at 03:45
  • 1
    Since C++17 there is [``](https://en.cppreference.com/w/cpp/filesystem) header instead. – heap underrun Jan 05 '21 at 03:46
  • You might find [A: experimental::filesystem linker error](https://stackoverflow.com/a/33159746) informative, *especially the updates* (even though the question is not really a duplicate of this one). – JaMiT Jan 05 '21 at 03:47

1 Answers1

0

With C++ 17 this is really easy.

Try the program below:

#include <iostream>
#include <filesystem>
#include <vector>
#include <iterator>
#include <algorithm>

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {

    // The start path. Use Program path
    const fs::path startPath{ fs::path(argv[0]).parent_path() };

    // Here we will store all file names
    std::vector<fs::path> files{};

    // Get all path names
    std::copy_if(fs::directory_iterator(startPath), {}, std::back_inserter(files), [](const fs::directory_entry& de) { return de.path().extension() == ".txt"; });

    // Output all files
    for (const fs::path& p : files) std::cout << p.string() << '\n';

    return 0;
}

We get the path name from argv[0] and then use the directory_iterator to go through all the files.

Then, we will copy the pathname to our resulting files vector, if the extension is ".txt".

I am not sure, what I should explain further. In case of questions, please ask.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
A M
  • 14,694
  • 5
  • 19
  • 44