在C++中,遍历文件有多种方法。以下是几种常见的方法:
<filesystem>库(C++17起可用):#include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { // 遍历指定目录下的所有文件和子目录 for (const auto& entry : fs::recursive_directory_iterator("path/to/directory")) { std::cout << entry.path() << std::endl; } return 0; } <dirent.h>头文件(仅适用于类Unix系统):#include <iostream> #include <dirent.h> int main() { DIR *dir; struct dirent *entry; // 打开目录 dir = opendir("path/to/directory"); if (dir == nullptr) { std::cerr << "Error opening directory" << std::endl; return 1; } // 遍历目录下的所有文件和子目录 while ((entry = readdir(dir)) != nullptr) { std::cout << entry->d_name << std::endl; } // 关闭目录 closedir(dir); return 0; } #include <iostream> #include <fstream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // 读取JSON文件并解析 std::ifstream file("path/to/file.json"); json j; file >> j; // 遍历JSON对象的所有键值对 for (const auto& [key, value] : j.items()) { std::cout << key << ": " << value << std::endl; } return 0; } 这些方法可以根据具体需求选择使用,其中<filesystem>库是最现代和最推荐的方法,因为它提供了跨平台的解决方案,并且易于使用。