在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>庫是最現代和最推薦的方法,因為它提供了跨平臺的解決方案,并且易于使用。