Append Text to an Existing File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Append Text to an Existing Text File

In this tutorial, you'll learn how to append text to an existing text file using the C programming language. Appending means adding new content to the end of a file without erasing what's already there — perfect for logs, journals, and any file that accumulates data over time. The entire trick is a single character in the fopen mode string: "a" instead of "w". Change "w" to "a" and everything else stays the same.

C program to append text to an existing text file using fopen with mode 'a', with step-by-step explanation.

📝 Problem Statement

Write a program in C to append text to an existing text file.

⚙️ How the Program Works

The program follows a simple open-write-close sequence:

  1. Ask for the filename (or hard-code it) and the text to append.
  2. Open the file in append mode: fopen("filename.txt", "a").
  3. Check for NULL in case the file cannot be opened or created.
  4. Write the new text with fputs() or fprintf().
  5. Close the file with fclose() to flush buffers and release the handle.

💻 Complete C Program

#include <stdio.h> int main(void) { FILE *fp; char filename[100]; char text[1024]; printf("Enter the filename to append to: "); scanf("%99s", filename); /* Clear the leftover newline from the previous scanf */ while (getchar() != '\n' && !feof(stdin)) ; printf("Enter the text to append: "); fgets(text, sizeof(text), stdin); /* Open the file in append mode. "a" preserves existing content and writes at the end. Creates the file if it does not exist. */ fp = fopen(filename, "a"); if (fp == NULL) { printf("Error: Could not open '%s' for appending.\n", filename); return 1; } /* Write the new text to the end of the file */ fputs(text, fp); fclose(fp); printf("Text appended to '%s' successfully.\n", filename); return 0; }

🖥️ Sample Output

Assume notes.txt already contains three lines from a previous session:

Contents of notes.txt before: First note: buy milk.
Second note: call mom.
Third note: finish the report.

Running the program to append a fourth line:

Console: Enter the filename to append to: notes.txt
Enter the text to append: Fourth note: water the plants.
Text appended to 'notes.txt' successfully.

After the program finishes, notes.txt contains:

Contents of notes.txt after: First note: buy milk.
Second note: call mom.
Third note: finish the report.
Fourth note: water the plants.

If notes.txt had not existed, the program would have created it with only the new line. The append mode creates the file on demand — no NULL error for a missing file.

🔍 Line-by-Line Explanation

Line / Code Explanation
scanf("%99s", filename) Reads a filename without spaces. %99s caps the input at 99 characters to prevent overflow.
while (getchar() != '\n' && !feof(stdin)); Discards the leftover newline from the previous scanf. Without this, fgets would immediately read an empty line.
fgets(text, sizeof(text), stdin) Reads a full line, including spaces, up to sizeof(text) - 1 characters. The trailing newline is kept in text, which is what we want.
fopen(filename, "a") Opens the file in append mode. Existing content is preserved; the write position starts at the end of the file.
if (fp == NULL) Detects failure — for example, a read-only directory or a permissions issue.
fputs(text, fp) Writes the entire string. The trailing newline from fgets is included, so the new content ends with a newline.
fclose(fp) Flushes the buffered text to disk and releases the file handle.
⚠️ Important: The single character 'a' in the fopen mode string is the entire difference between "append" and "overwrite." Using "w" on an existing file would erase its content before writing. This is the #1 file-handling bug in beginner code.

📂 Append Mode vs Write Mode

The difference between the two modes is subtle in code but dramatic in effect:

Mode Existing file Missing file Write position
"w" Truncates to 0 bytes Creates it Start of file
"a" Preserves content Creates it End of file
"w+" Truncates to 0 bytes Creates it Start (read/write)
"a+" Preserves content Creates it End (read/write)

The same pattern applies to binary mode: "ab" for appending binary data, "wb" for overwriting binary data. See Assignment 3 for the binary version.

🐛 Common Pitfalls

  • Using "w" by mistake: This is the single most common bug. The file opens successfully but its content is erased. If you don't see the old content after running the program, you used "w".
  • Leftover newline from scanf: After scanf("%s"), a newline is left in stdin. If you call fgets without flushing it first, you'll read an empty line. The while (getchar() != '\n') loop fixes this.
  • Forgetting the trailing newline: If the existing file ends with text but no newline, the appended text will be glued to the last line. Either ensure the existing file ends with \n, or prepend '\n' to the new text.
  • Missing NULL check: Append mode still fails if the directory is not writable. Always check the return value.
  • Not closing: Without fclose, buffered text may never reach the disk. The file may appear unchanged until the program exits.

💡 Tips & Best Practices

  • Use "a" for logs, journals, and any file that accumulates data.
  • If you want to append content and then read the file back in the same program, use "a+" and fseek(fp, 0, SEEK_SET) before reading.
  • Always check fopen for NULL, even in append mode.
  • Consider adding a timestamp or a separator (e.g., "\n---\n") between appended entries for readability.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch format-string mistakes.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 1. Create a New Text File and Write Text in It
  • 3. Append Data to an Existing Binary File
  • 4. Read and Display the Contents of a Text File
  • 15. Copy the Contents of One Text File into Another
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 13. Decrypt the Contents of an Encrypted Text File   ||   Next Problem: -->> 15. Copy the Contents of One Text File into Another

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.