检查路径中的所有文件大小(C++)

Check all files sizes in a path (C++)

我正在尝试循环以便我的程序可以获取文件夹中所有文件的权重,如果其中任何一个的权重等于 X,它就会执行一个操作,我需要知道如何我可以像这样循环,我有一个函数来知道文件大小是多少

std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}

这里有一个简短的示例程序,演示了如何使用 C++17 的 <filesystem> 库迭代目录。如果您的编译器是最新的,它应该毫无问题地支持 C++17。

#include <filesystem>
#include <iostream>

int main() {
  namespace fs = std::filesystem;

  fs::path pwd("");  // Current directory program was executed from
  pwd = fs::absolute(pwd);

  for (auto& i : fs::directory_iterator(pwd)) {
    try {
      if (fs::file_size(i.path()) / 1024 > 2048) {
        std::cout << i.path() << " is larger than 2MB\n";
      }
    } catch (fs::filesystem_error& e) {
      std::cerr << e.what() << '\n';
    }
  }
}

这是目录的内容:

.
├── a.out
├── fiveKB
├── fourMB
├── main.cpp
└── oneMB

0 directories, 5 files

以及有关文件的信息:

drwxr-xr-x   7 user  staff   224B Jul 29 22:11 ./
drwxr-xr-x  13 user  staff   416B Jul 29 21:59 ../
-rwxr-xr-x   1 user  staff    47K Jul 29 22:10 a.out*
-rw-r--r--   1 user  staff   5.0K Jul 29 21:58 fiveKB
-rw-r--r--   1 user  staff   4.0M Jul 29 21:59 fourMB
-rw-r--r--   1 user  staff   450B Jul 29 22:11 main.cpp
-rw-r--r--   1 user  staff   1.0M Jul 29 21:59 oneMB

最后,输出:
"/Users/user/Documents/tmp/test/fourMB" is larger than 2MB