Yes, std::filesystem::directory_iterator
can be used with relative paths. When using relative paths, they are resolved relative to the current working directory of the program.
Here’s an example using a relative path:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path relative_path{"."}; Current directory
fs::directory_iterator start{relative_path};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string() << '\n';
}
}
.\file1.txt
.\file2.txt
.\subdirectory
"."
for the current directory or "../"
for the parent directory).std::filesystem::directory_iterator
with the relative path.You can combine relative paths with std::filesystem::absolute()
to get the absolute path:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path relative_path{"."};
fs::path absolute_path =
fs::absolute(relative_path);
std::cout << "Absolute path: "
<< absolute_path.string() << '\n';
fs::directory_iterator start{absolute_path};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string() << '\n';
}
}
Absolute path: C:\current\working\directory
C:\current\working\directory\file1.txt
C:\current\working\directory\file2.txt
C:\current\working\directory\subdirectory
You can change the current working directory using std::filesystem::current_path()
:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path new_cwd{R"(c:\test)"};
fs::current_path(new_cwd);
// Current Directory
fs::directory_iterator start{"."};
fs::directory_iterator end{};
for (auto iter{start}; iter != end; ++iter) {
std::cout << iter->path().string() << '\n';
}
}
.\file1.txt
.\file2.txt
.\subdirectory
Using std::filesystem::directory_iterator
with relative paths is straightforward and provides flexibility in navigating and processing file systems relative to your program’s current working directory.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterating through the file system, using directory iterators and recursive directory iterators