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

C语言开发文本编辑器写入文件无法追加仅覆盖如何解决?

问题解决方法

核心问题1:文件打开模式错误

你当前使用的fopen("texteditor.txt","w")中,"w"写模式会默认清空已存在的文件内容后再写入,这是你第二次运行程序后原有内容丢失的直接原因。

  • 解决方案:如果需要在文件末尾追加内容,将打开模式替换为"a"即可;如果需要支持随机读写且不清空原有内容,可使用"r+"(要求文件必须已存在)或"a+"(文件不存在时自动创建)。

核心问题2:内存数据无法跨程序运行保留

你定义的textbuffer全局数组存储在进程内存空间中,程序退出后内存会被系统回收,第二次运行时textbuffer会被重新初始化,不会保留上一次运行写入的内容,你当前的链表逻辑完全没有生效。

  • 解决方案:
    1. 程序启动时先读取texteditor.txt的已有内容,加载到textbuffer数组中重建链表
    2. 写入文件时遍历整个已使用的链表节点,把全部文本内容写入,而非仅写入当前插入的单行内容

其他需要修正的逻辑错误

  • 遍历textbuffer的循环条件i<=25会触发数组越界:数组长度为25,合法下标范围是0~24,需要将循环条件改为i<25
  • textbuffer[i].statement==NULL的判断逻辑错误:statement是字符数组而非指针,判断空内容应改为textbuffer[i].statement[0] == '\0'
  • 插入逻辑未做长度校验:传入的stat如果长度超过39,strcpy会触发缓冲区溢出,建议替换为strncpy并手动补字符串结束符

修改后可实现多次运行内容累加的示例代码

#include <stdio.h>
#include <string.h>

struct node
{
    char statement[40];
    int next;
};
struct node textbuffer[25];

int free_head;
int inuse_head;

// 程序启动时加载已有文件内容到textbuffer重建链表
void load_file() {
    FILE *file = fopen("texteditor.txt", "r");
    if (file == NULL) return;
    int line = 0;
    while (fgets(textbuffer[line].statement, 40, file) != NULL && line < 25) {
        // 去掉fgets读取的换行符
        textbuffer[line].statement[strcspn(textbuffer[line].statement, "\n")] = '\0';
        textbuffer[line].next = line + 1;
        line++;
    }
    inuse_head = 0;
    free_head = line;
    fclose(file);
}

void insert(int line, char* stat)
{
    if (line <0 || line >=25) return;
    // 长度校验避免缓冲区溢出
    strncpy(textbuffer[line].statement, stat, 39);
    textbuffer[line].statement[39] = '\0';
    textbuffer[line].next = line+1;

    // 重新计算空闲节点头和已使用节点头
    free_head = 0;
    while(free_head <25 && textbuffer[free_head].statement[0] != '\0') {
        free_head++;
    }
    inuse_head = 0;
    while(inuse_head <25 && textbuffer[inuse_head].statement[0] == '\0') {
        inuse_head++;
    }

    // 重写全量内容到文件,避免追加导致的内容重复
    FILE *file = fopen("texteditor.txt","w");
    if(file!=NULL)
    {
        int cur = inuse_head;
        while(cur <25 && textbuffer[cur].statement[0] != '\0') {
            fprintf(file, "%s\n", textbuffer[cur].statement);
            cur = textbuffer[cur].next;
        }
    }
    else
    {
        printf("File couldn't open.");
    }
    fclose(file);
}


int main()
{
    load_file();
    insert(free_head,"Hello World");
    return 0;   
}

内容的提问来源于stack exchange,提问作者Oğulcan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:15:07