Search code examples
cline

How to allow other sentences to be in a file?


In this code whenever I write a new sentence, it replaces the previous sentence in a file that I put earlier. I want to not replace the previous sentence and also allow other sentences in that file line after line.

#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;
}

Solution

  • Open the file in append mode.

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

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