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

C++不使用ios::app追加文本文件时文件被清空的问题

问题分析与解决方案

问题根源

你的代码存在几个关键错误,导致文件内容丢失:

  1. 变量名不匹配:定义了Vorhandene_Woerter但实际使用的是未初始化的Words_in_List,读取的内容根本没被保存;同时std::getline(data_wordlist_in, Wort);中的Wort未定义,属于拼写错误。
  2. 读取逻辑错误:用do-while(!data_wordlist_in.eof())读取文件会导致异常,且第一次读取的变量未定义,直接跳过了第一行内容,最终Words_in_List为空。
  3. 写入时覆盖内容:因为Words_in_List为空,写入时只会保留新输入的单词,原文件内容被覆盖,看起来像是被清空。

修正后的代码

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

using namespace std;

int append_new_word() {
    // 读取文件所有内容
    ifstream data_wordlist_in("woerterliste");
    if (!data_wordlist_in) {
        cout << "文件不存在!" << endl;
        return 1;
    }

    string Word;
    string Words_in_List;

    // 正确遍历每一行,避免eof判断的坑
    while (getline(data_wordlist_in, Word)) {
        if (!Words_in_List.empty()) {
            Words_in_List += "\n";
        }
        Words_in_List += Word;
    }

    data_wordlist_in.close();

    // 写入原内容+新单词
    ofstream data_wordlist_out("woerterliste");
    if (!data_wordlist_out) {
        cout << "文件无法打开!" << endl;
        return 1;
    }

    string new_word_in_list;
    cout << "\n请输入要追加的单词: ";
    cin >> new_word_in_list;

    // 处理空文件情况,避免多余空行
    if (!Words_in_List.empty()) {
        data_wordlist_out << Words_in_List << "\n";
    }
    data_wordlist_out << new_word_in_list;

    data_wordlist_out.close();
    return 0;
}

int main() {
    append_new_word();
    return 0;
}

关键改动说明

  • 统一变量命名,修复拼写错误,确保读取的内容能正确存入字符串。
  • 用while (getline(...))替代do-while(!eof()),这是C++读取文件行的标准写法,能准确处理所有行,避免漏读或重复读取。
  • 拼接字符串时判断是否为空,避免开头出现多余的换行符。
  • 写入时处理空文件场景,保证文件格式始终是每行一个单词。
  • 补充main函数和函数返回值,让程序可以正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 15:40:31