溫馨提示×

c++遍歷文件有哪些常見方法

c++
小樊
132
2024-12-06 04:18:02
欄目: 編程語言

在C++中,遍歷文件有多種方法。以下是幾種常見的方法:

  1. 使用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;
}
  1. 使用C++標準庫中的<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;
}
  1. 使用第三方庫,如nlohmann/json庫來處理JSON文件:
#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>庫是最現代和最推薦的方法,因為它提供了跨平臺的解決方案,并且易于使用。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女