如何允许其他句子出现在文件中?

问题描述

在此代码中,每当我写一个新句子时,它就会替换我之前放置的文件中的前一个句子。我不想替换前一个句子,也不允许该文件中的其他句子逐行显示

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

int main() {
    char sentence[1000];
    // creating file pointer to work with files
    FILE *fptr;
    // opening file in writing mode
    fptr = fopen("file.txt","w");
    // exiting program 
    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;
}

解决方法

以追加模式打开文件。

fptr = fopen("file.txt","a");

https://en.cppreference.com/w/c/io/fopen