C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Append to a file

C Program: Append to a file

C

#include <stdio.h>

 

int main() {

    FILE *fp;

    char data[200];

 

    // Step 1: Open file in append mode

    fp = fopen("output.txt", "a");

 

    // Step 2: Check if file is opened successfully

    if (fp == NULL) {

        printf("Error! Unable to open file.\n");

        return 1;

    }

 

    // Step 3: Get text from user to append

    printf("Enter text to append to the file:\n");

    fgets(data, sizeof(data), stdin);

 

    // Step 4: Write the text to the file

    fputs(data, fp);

 

    // Step 5: Close the file

    fclose(fp);

 

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

 

    return 0;

}

Output

 
INPUT :
Enter text to append to the file:
This line was added later.

File (output.txt) before running program:
Hello, this is a file write example in C. 

File after appending: :

Hello, this is a file write example in C.
This line was added later. 

Explanation

Step

Description

1

Opens file in append mode using "a". If the file doesn’t exist, it will be created.

2

Checks whether the file was opened successfully.

3

Takes user input using fgets().

4

Appends data to the end of the file using fputs().

5

Closes the file properly with fclose().