boost::filesystem::directory_iterator
的输入路径不一定必须是绝对路径!也可以使用相对路径来创建 directory_iterator
对象,只要该相对路径是,从当前工作目录出发的有效路径。
详细说明
-
绝对路径:从文件系统的根目录开始的完整路径。例如:
/home/user/documents
(在类 Unix 系统上)或C:\Users\User\Documents
(在 Windows 上)。 -
相对路径:相对于当前工作目录的路径。例如:
documents
或../documents
。
示例代码
以下是一个使用相对路径和绝对路径的示例:
#include <boost/filesystem.hpp>
#include <iostream>
int main() {
// 使用绝对路径
boost::filesystem::path absolute_path("/home/user/documents");
for (boost::filesystem::directory_iterator it(absolute_path), end; it != end; ++it) {
std::cout << it->path() << std::endl;
}
// 使用相对路径
boost::filesystem::path relative_path("documents");
for (boost::filesystem::directory_iterator it(relative_path), end; it != end; ++it) {
std::cout << it->path() << std::endl;
}
return 0;
}
总结
- 可以使用相对路径或绝对路径,来初始化
boost::filesystem::directory_iterator
对象。 - 确保相对路径是,从当前工作目录出发的有效路径,以避免
路径无效
的错误。