蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 <fstream> 文本写入、逐行读取、追加模式、ate/trunc 语义及二进制结构体读写

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-fstream.cpp
explore-cpp-libs-fstream.cpp157 行
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

struct Record {
    int id;
    double score;
};

} // namespace lab

int main() {
    std::vector<lab::Case> cases;
    const std::string txt_path = "/tmp/lab_ch49_example.txt";
    const std::string bin_path = "/tmp/lab_ch49_record.bin";

    // Case 1: Write text file (ios::out) and read lines back (ios::in + getline)
    {
        std::fstream out_f;
        out_f.open(txt_path, std::ios::out);
        out_f << "Hello, World!\n" << "This is a test file.\n";
        out_f.close();
    }
    std::vector<std::string> lines1;
    {
        std::fstream in_f;
        in_f.open(txt_path, std::ios::in);
        std::string line;
        while (std::getline(in_f, line)) {
            lines1.push_back(line);
        }
        in_f.close();
    }
    bool ok1 = (lines1 == std::vector<std::string>{"Hello, World!", "This is a test file."});
    cases.push_back({
        "fstream_write_and_read_lines",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: Append to file (ios::app)
    {
        std::fstream app_f;
        app_f.open(txt_path, std::ios::app);
        app_f << "Appending this line to the file.\n";
        app_f.close();
    }
    std::vector<std::string> lines2;
    {
        std::fstream in_f(txt_path, std::ios::in);
        std::string line;
        while (std::getline(in_f, line)) lines2.push_back(line);
    }
    bool ok2 = (lines2.size() == 3) && (lines2[2] == "Appending this line to the file.");
    cases.push_back({
        "fstream_append_mode",
        lab::jbool(true),
        lab::jbool(ok2),
        ok2
    });

    // Case 3: ios::ate initial position at EOF & ios::trunc clears file
    std::streampos ate_pos = 0;
    {
        std::fstream ate_f(txt_path, std::ios::in | std::ios::ate);
        ate_pos = ate_f.tellg();
    }
    std::streampos trunc_pos = -1;
    {
        std::fstream tr_f(txt_path, std::ios::out | std::ios::trunc);
        tr_f.close();
        std::fstream chk_f(txt_path, std::ios::in | std::ios::ate);
        trunc_pos = chk_f.tellg();
    }
    bool ok3 = (ate_pos > 0) && (trunc_pos == 0);
    cases.push_back({
        "fstream_ate_and_trunc_modes",
        lab::jbool(true),
        lab::jbool(ok3),
        ok3
    });

    // Case 4: Binary roundtrip (ios::binary) and /tmp cleanup
    lab::Record wrec{7, 98.5}, rrec{0, 0.0};
    {
        std::fstream bf(bin_path, std::ios::out | std::ios::binary);
        bf.write(reinterpret_cast<const char*>(&wrec), sizeof(wrec));
    }
    {
        std::fstream bf(bin_path, std::ios::in | std::ios::binary);
        bf.read(reinterpret_cast<char*>(&rrec), sizeof(rrec));
    }
    int rm1 = std::remove(txt_path.c_str());
    int rm2 = std::remove(bin_path.c_str());
    bool ok4 = (rrec.id == 7 && rrec.score == 98.5) && (rm1 == 0 && rm2 == 0);
    cases.push_back({
        "fstream_binary_roundtrip_and_cleanup",
        lab::jbool(true),
        lab::jbool(ok4),
        ok4
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-fstream-lab/explore-cpp-libs-fstream.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-fstream.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2349.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习