【问题标题】:How to keep the data in file.txt?如何将数据保存在 file.txt 中?
【发布时间】:2020-09-09 18:10:19
【问题描述】:

即使我再次运行代码,我也想将数据存储在 file.txt 中。每当我运行代码时,它都会删除所有以前的数据。

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000];  
    FILE *fptr = fopen("file.txt", "w");

    if (fptr == NULL) {
        printf("Error!");
        exit(1);
    }

    printf("Enter a sentence:\n");
    fgets(sentence, sizeof(sentence), stdin);
    fprintf(fptr, "%s", sentence);
    fclose(fptr);

    return 0;
}

【问题讨论】:

  • 您不希望删除以前的数据。所以你想要什么?要将新数据附加到现有内容?
  • 我不想在输入新数据时替换旧数据。我想在每次输入数据时存储。
  • 你只需要将模式写入更改为追加

标签: c function file fgets


【解决方案1】:

以“追加”模式打开文件:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char sentence[1000];  
    FILE *fptr = fopen("file.txt", "a"); /*  <===== changed from "w" to "a" */

    if (fptr == NULL) {
        printf("Error!");
        exit(1);
    }

    printf("Enter a sentence:\n");
    fgets(sentence, sizeof(sentence), stdin);
    fprintf(fptr, "%s", sentence);
    fclose(fptr);

    return 0;
}

现在将在文件末尾添加新数据。

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多