使用 ifstream::open() 读取 JSON 文件

本教程展示如何使用 C++ 的 ifstream::open() 函数打开并读取名为 'x.json' 的 JSON 文件。

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream file;
    std::string filename = 'x.json';
    file.open(filename);

    if (!file.is_open()) {
        std::cerr << "Failed to open file: " << filename << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    file.close();
    return 0;
}

在上述代码中,std::ifstream 是 C++ 标准库中用于读取文件的类。我们首先创建一个 std::ifstream 对象,然后使用其 open() 方法打开文件 'x.json'。如果打开文件失败,我们输出错误信息并返回 1。

接下来,我们使用 std::getline() 方法从文件中逐行读取内容,并将每行内容输出到控制台。最后,我们使用 close() 方法关闭文件。

注意:

  • 该示例只展示了读取 JSON 文件内容,并没有对 JSON 数据进行解析。
  • 你需要使用其他库,例如 JSON for Modern C++,来解析 JSON 数据。
  • 文件 'x.json' 需要存在于当前目录下。
C++ 使用 ifstream::open() 读取 JSON 文件

原文地址: https://www.cveoy.top/t/topic/nvxY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录