C++终于在17中增加了对文件系统的支持,在这之前C++程序员只能使用POSIX接口或者windowsAPI去做一些目录操作。 下面来看看怎么使用吧。
注:
- 编译器版本要求:gcc>=8 clang>=7 MSVC>=19.14
- 头文件为 #include <filesystem>,命名空间为std::filesystem
- 官方文档 https://en.cppreference.com/w/cpp/filesystem
filesystem中,所有的文件、路径,都抽象成了path这个类,其成员函数可以获取各种类型的路径名、拼接路径名、修改扩展名等。并且由于重载了operator/=,因此还可以用/符号来拼接两个path对象。这个类可以理解成针对路径进行特化的一个字符串类,它不包含一些更高级的操作。举例:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path exampleFile = "D:\\_workspace\\png\\1.png";
printf("string: %s\n", exampleFile.string().c_str());
printf("generic_string: %s\n", exampleFile.generic_string().c_str());
printf("root_name: %s\n", exampleFile.root_name().string().c_str());
printf("root_directory: %s\n", exampleFile.root_directory().string().c_str());
printf("root_path: %s\n", exampleFile.root_path().string().c_str());
printf("relative_path: %s\n", exampleFile.relative_path().string().c_str());
printf("parent_path: %s\n", exampleFile.parent_path().string().c_str());
printf("filename: %s\n", exampleFile.filename().string().c_str());
printf("stem: %s\n", exampleFile.stem().string().c_str());
printf("extension: %s\n", exampleFile.extension().string().c_str());
}
输出为:
string: D:\_workspace\png\1.png
generic_string: D:/_workspace/png/1.png
root_name: D:
root_directory: \
root_path: D:\
relative_path: _workspace\png\1.png
parent_path: D:\_workspace\png
filename: 1.png
stem: 1
extension: .png
更高级的操作需要用到directory_entry这个类,它包含的操作有:检查路径是否存在、检查路径的类型(是目录还是文件还是软链接)、获取路径占用空间的大小、获取路径的修改时间等。
当需要遍历一个目录时,需要用到directory_iterator类。
下面结合directory_entry和directory_iterator举个栗子,比如我要遍历目录A,获取A中的所有后缀为png的图片,在目录B中创建与其文件名相同但后缀不同的jpg文件:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
fs::path srcDir = "D:\\_workspace\\png";
fs::path dstDir = "D:\\_workspace\\jpg";
if (!fs::exists(srcDir)) {
return -1;
}
if (!fs::exists(dstDir)) {
fs::create_directory(dstDir); //不存在则创建
}
// 遍历directory_iterator获取每个directory_entry
for (const fs::directory_entry &entry: fs::directory_iterator(srcDir)) {
// 若是文件,且后缀是png
if (entry.is_regular_file() and entry.path().extension() == ".png") {
printf("%s\n", entry.path().string().c_str());
// 替换后缀
fs::path dstFileName = entry.path().filename().replace_extension("jpg");
// 拼接生成新的文件名
fs::path dst = dstDir / dstFileName;
printf("%s\n", dst.string().c_str());
}
}
}