Hello, sorry but I need help on how to browse through folders and subfolders in c++ searching for certain file.
Thanks in advance
Last edited on
In C++17 you can use std::filesystem.
See:
https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::create_directories("sandbox/a/b");
std::ofstream("sandbox/file1.txt");
fs::create_symlink("a", "sandbox/syma");
for(auto& p: fs::recursive_directory_iterator("sandbox"))
std::cout << p.path() << '\n';
fs::remove_all("sandbox");
}
| |
Possible output:
"sandbox/a"
"sandbox/a/b"
"sandbox/file1.txt"
"sandbox/syma" |
To compare with just the filename, use path().filename()
See:
https://en.cppreference.com/w/cpp/filesystem/path/filename
Last edited on
What if I want to search for a certain file within folders and subfolders.....
In that case, you can use code like this:
1 2 3 4 5 6 7
|
for(auto& p: fs::recursive_directory_iterator("folder_to_search"))
{
if ( p.path().filename() == searchValue)
{
// do something
}
}
| |
Last edited on