Use Relative Paths with Directory Iterator
Can directory_iterator
be used with relative paths?
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
Steps to Use Relative Paths:
- Specify Relative Path: Use a relative path (e.g.,
"."
for the current directory or"../"
for the parent directory). - Initialize Iterator: Create a
std::filesystem::directory_iterator
with the relative path. - Iterate and Process: Loop through the directory entries and process them as needed.
Combining with Absolute Paths:
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
Changing the Current Working Directory:
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
Key Considerations:
- Path Resolution: Relative paths are resolved based on the current working directory.
- Portability: Be mindful of the current working directory, especially when running the program from different locations or environments.
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.
Directory Iterators
An introduction to iterating through the file system, using directory_iterator
and recursive_directory_iterator
.