You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac OS环境下C++如何仅修改文本文件中的指定部分内容?

方案1:等长字符串局部覆盖(适配你当前场景)

你当前要替换的Jack和John长度完全一致,都是4个字符,这种场景可以直接定位到目标位置做局部覆盖写入,不需要重写文件其他内容:

#include <fstream>
#include <string>

int main() {
    std::fstream file("yourname.txt", std::ios::in | std::ios::out);
    if (!file.is_open()) return 1;

    std::string line;
    std::streampos line_start_pos;
    // 逐行扫描找到目标行
    while (std::getline(file, line)) {
        if (line.find("My name is ") != std::string::npos) {
            // 计算名字的起始偏移量:当前行起始位置 + 固定前缀长度
            std::streampos target_pos = line_start_pos + std::string("My name is ").length();
            // 移动写入指针到目标位置
            file.seekp(target_pos);
            // 直接覆盖写入新名字
            file << "John";
            break;
        }
        line_start_pos = file.tellg();
    }
    file.close();
    return 0;
}

注意:该方案仅适用于替换前后内容长度完全相同的场景,如果后续要替换的名字长度变化,会出现残留字符问题,建议使用方案2


方案2:通用动态修改方案(适配任意长度替换)

该方案不需要硬编码文件内的日期等动态内容,只需要把文件内容读入内存做替换后再写回,灵活性更高:

#include <fstream>
#include <string>
#include <sstream>

int main() {
    // 读取全部文件内容到内存
    std::ifstream read_file("yourname.txt");
    if (!read_file.is_open()) return 1;
    std::stringstream buffer;
    buffer << read_file.rdbuf();
    std::string content = buffer.str();
    read_file.close();

    // 替换目标字符串,不影响其他内容
    size_t pos = content.find("My name is Jack");
    if (pos != std::string::npos) {
        content.replace(pos, std::string("My name is Jack").length(), "My name is John");
    }

    // 修改完成后写回文件
    std::ofstream write_file("yourname.txt");
    if (!write_file.is_open()) return 1;
    write_file << content;
    write_file.close();
    return 0;
}

内容的提问来源于stack exchange,提问作者Mehmet Ozen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:06:03