文件系统的相关操作一直以来都是跨平台开发的难点,不同的平台有不同的系统 API 设计,往往需要自己封装来实现统一接口。现代 C++ 提供了文件系统库,大大的方便了开发者,统一了各个平台的文件、目录、目录遍历等编程操作。

🐭 总览

C++ 文件系统库主要由下面几个部分组成:

std::filesystem::path std::filesystem::file_status std::filesystem::directory_entry std::filesystem::directory_iterator https://en.cppreference.com/w/cpp/filesystem

当然还有其他的一些辅助类和方法,其中最重要的就是 path 类,C++ 的整个文件系统库都是围绕着 path 类建立起来的。
本文不会介绍文件系统库的方方面面,只介绍其中比较重要的部分。比如下面的内容就不会介绍:

  1. 文件、目录的创建、拷贝、删除、移动
  2. 文件系统空间信息的获取
  3. 文件、目录的软链接、硬链接
  4. 零时文件、目录的创建和使用

    🐂 path 类介绍

    path 类是整个文件系统库的核心,path 表示的是一种路径,它可以表示各种类型的文件,也可以表示目录。POSIX 系统和 windows 系统下的 path 是有区别的,主要区别如下图:
    fs.png ```cpp

    include

    include

int main() { // make sure the path exists before run the program namespace fs = std::filesystem; std::cout.setf(std::ios_base::boolalpha);

// set current path, string() can remove std::quoted() impact fs::current_path(“/Users/jtcheng/work/code/cpp/leetcode”); std::cout << fs::current_path().string() << std::endl; // /Users/jtcheng/work/code/cpp/leetcode

// absolute path fs::path p0(“/Users/jtcheng/work/code/cpp/leetcode”); p0 /= “main.cpp”; std::cout << p0.is_absolute() << std::endl; // true std::cout << p0.filename() << std::endl; // “main.cpp” std::cout << p0.extension() << std::endl; // “.cpp” std::cout << p0.stem() << std::endl; // “main”

// relative path fs::path p1(“../.././cpp/leetcode/main.cpp”); std::cout << p1.is_relative() << std::endl; // true std::cout << fs::equivalent(p0, p1) << std::endl; // true std::cout << p1 << std::endl; // “../.././cpp/leetcode/main.cpp”

// normalized path std::cout << fs::canonical(p1) << std::endl; std::cout << fs::absolute(p1) << std::endl; // “/Users/jtcheng/work/code/cpp/leetcode/main.cpp” // “/Users/jtcheng/work/code/cpp/leetcode/../.././cpp/leetcode/main.cpp”

// p3 with a trailing directory separator fs::path p2(“/Users/jtcheng/work/code/cpp/leetcode/Debug”); fs::path p3(“/Users/jtcheng/work/code/cpp/leetcode/Debug/“); std::copy(p2.begin(), p2.end(), std::ostream_iterator(std::cout, “ “)); // “/“ “Users” “jtcheng” “work” “code” “cpp” “leetcode” “Debug” std::cout << std::endl; std::copy(p3.begin(), p3.end(), std::ostream_iterator(std::cout, “ “)); // “/“ “Users” “jtcheng” “work” “code” “cpp” “leetcode” “Debug” “” std::cout << std::endl;

return 0; }

  1. <a name="PevtW"></a>
  2. ## 🐯 file_status 类介绍
  3. 针对一个 path 对象,我们可以得到其 file_status 对象,file_status 对象包含了文件类型和文件权限信息。<br />**文件类型信息:**
  4. ```cpp
  5. #include <filesystem>
  6. #include <iostream>
  7. int main() {
  8. namespace fs = std::filesystem;
  9. auto type = [](const fs::file_type &t) {
  10. switch (t) {
  11. case fs::file_type::block:
  12. return 'b';
  13. case fs::file_type::character:
  14. return 'c';
  15. case fs::file_type::directory:
  16. return 'd';
  17. case fs::file_type::fifo:
  18. return 'p';
  19. case fs::file_type::regular:
  20. return 'f';
  21. case fs::file_type::socket:
  22. return 's';
  23. case fs::file_type::symlink:
  24. return 'l';
  25. case fs::file_type::none:
  26. case fs::file_type::not_found:
  27. case fs::file_type::unknown:
  28. default:
  29. return '?';
  30. }
  31. };
  32. fs::path p0("/Users/jtcheng/work/code/cpp/leetcode/main.cpp");
  33. std::cout << type(fs::status(p0).type()) << std::endl; // f
  34. fs::path p1("/Users/jtcheng/work/code/cpp/leetcode");
  35. std::cout << type(fs::status(p1).type()) << std::endl; // d
  36. std::cout << type(fs::status("/dev/null").type()) << std::endl; // c
  37. fs::path p2 = p1 / "nonexistent.txt";
  38. std::cout << type(fs::status(p2).type()) << std::endl; // ?
  39. return 0;
  40. }

文件权限信息:

  1. #include <filesystem>
  2. #include <iostream>
  3. #include <string>
  4. int main() {
  5. namespace fs = std::filesystem;
  6. auto permissions = [](const fs::perms &p) {
  7. auto check = [&p](const fs::perms &bit, const char c) {
  8. return (p & bit) == fs::perms::none ? '-' : c;
  9. };
  10. return std::string{
  11. check(fs::perms::owner_read, 'r'), check(fs::perms::owner_write, 'w'),
  12. check(fs::perms::owner_exec, 'x'), check(fs::perms::group_read, 'r'),
  13. check(fs::perms::group_write, 'w'), check(fs::perms::group_exec, 'x'),
  14. check(fs::perms::others_read, 'r'), check(fs::perms::others_write, 'w'),
  15. check(fs::perms::others_exec, 'x')};
  16. };
  17. fs::path p0("/Users/jtcheng/work/code/cpp/leetcode/main.cpp");
  18. const fs::perms fp0 = fs::status(p0).permissions();
  19. std::cout << permissions(fp0) << std::endl;
  20. // rw-r--r--
  21. fs::path p1("/Users/jtcheng/work/code/cpp/leetcode");
  22. std::cout << permissions(fs::status(p1).permissions()) << std::endl;
  23. // rwxr-xr-x
  24. // set file permission to 777
  25. fs::permissions(p0, fs::perms::owner_all | fs::perms::group_all | fs::perms::others_all);
  26. std::cout << permissions(fs::status(p0).permissions()) << std::endl;
  27. // rwxrwxrwx
  28. // restore file permission to 644
  29. fs::permissions(p0, fp0);
  30. return 0;
  31. }

🐰 目录遍历操作

目录可以通过一个 path 对象来初始化,然后可以通过目录迭代器来遍历目录里面的内容,也可以递归的遍历多级目录。目录迭代器非常有用,如果没有目录迭代器,遍历一个目录需要操作系统 API 的支持。
一个简单的文件统计程序:

  1. #include <filesystem>
  2. #include <iostream>
  3. #include <map>
  4. #include <sstream>
  5. #include <string>
  6. int main() {
  7. using namespace std;
  8. using namespace filesystem;
  9. auto sizestr = [](const size_t size) {
  10. stringstream ss;
  11. if (size >= 1000000) {
  12. ss << (size / 1000000) << 'M';
  13. } else if (size >= 1000) {
  14. ss << (size / 1000) << 'K';
  15. } else {
  16. ss << size << 'B';
  17. }
  18. return ss.str();
  19. };
  20. auto extstats = [](const path &d) {
  21. map<string, pair<size_t, size_t>> m;
  22. auto dopts = directory_options::skip_permission_denied;
  23. for (const auto &entry : recursive_directory_iterator{d, dopts}) {
  24. const path p{entry.path()};
  25. const string ext{p.extension().string()};
  26. if (is_directory(status(p)) || ext.empty()) {
  27. continue;
  28. }
  29. auto &[size, count] = m[ext];
  30. size += file_size(p);
  31. count += 1;
  32. };
  33. return m;
  34. };
  35. path dir("/Users/jtcheng/Documents/cppreference");
  36. cout << "TYPE NUM SIZE AVG_SIZE\n" << string(36, '-') << '\n';
  37. for (const auto &[ext, stats] : extstats(dir)) {
  38. const auto &[size, count] = stats;
  39. cout << setw(6) << left << ext << setw(8) << right << count << setw(10)
  40. << sizestr(size) << setw(10) << sizestr(size / count) << endl;
  41. }
  42. #if 0
  43. TYPE NUM SIZE AVG_SIZE
  44. ------------------------------------
  45. .css 2 83K 41K
  46. .gif 7 6K 902B
  47. .html 5237 221M 42K
  48. .ico 1 2K 2K
  49. .js 3 13K 4K
  50. .php 1 743B 743B
  51. .png 36 363K 10K
  52. .svg 59 337K 5K
  53. .ttf 2 843K 421K
  54. #endif
  55. return 0;
  56. }