Problem Solving using C Language

0 of 77 lessons complete (0%)

File Handling

Appending to a File

#include <stdio.h>

int main() {
    FILE *filePtr;

    // Open the file in append mode ("a")
    filePtr = fopen("sample.txt", "a");

    // Check if the file opened successfully
    if (filePtr == NULL) {
        printf("Error! Could not open file.\n");
        return 1;
    }

    // Append data to the file
    fprintf(filePtr, "Appending this line to the file.\n");

    // Close the file
    fclose(filePtr);

    printf("Data appended to the file successfully.\n");

    return 0;
}

This program appends a new line of text to the existing sample.txt file.

Explanation:

  • "a" mode ensures that new data is added to the end of the file without overwriting existing content.