Course contentsShow
← C
Lesson 713 of 1,21910. Input and OutputFree lesson

The difference between w and a modes

The difference between w and a modes

What you'll learn: You will understand how to choose between overwriting a file from scratch and adding new data to the end of an existing file.

When you use the fopen() function in C, the "mode" argument acts like a set of instructions for the computer's cursor. Two of the most common modes for writing data are "w" (write) and "a" (append). Choosing the wrong one can mean the difference between keeping your data and losing it forever.

The Whiteboard vs. The Notebook

Think of the "w" (Write) mode like a clean whiteboard. Every time you walk up to a whiteboard to write a new message, the first thing you do is grab an eraser and wipe the board completely blank. Even if the file already had ten pages of important text, opening it with "w" instantly deletes everything. It creates a fresh, empty file for you to start over.

Think of the "a" (Append) mode like a spiral notebook. When you want to add a new entry, you don't rip out the previous pages. Instead, you flip to the very last line of the last page and start writing from there. The existing data remains untouched, and your new information is simply tacked onto the end.

How it looks in C

Here is a conceptual look at how these modes behave when you open a file:

#include <stdio.h>

int main() {
    // Mode "w": Overwrites the file. 
    // If "log.txt" exists, its old content is DELETED.
    FILE *fileW = fopen("log.txt", "w");
    fprintf(fileW, "This is a fresh start.\n");
    fclose(fileW);

    // Mode "a": Adds to the file.
    // "This is a fresh start" stays, and the new line follows it.
    FILE *fileA = fopen("log.txt", "a");
    fprintf(fileA, "This line is added to the end.\n");
    fclose(fileA);

    return 0;
}

When to use which?

You should use "w" when you are creating a brand-new document or when you want to replace an old version of a file entirely—for example, saving a high score in a game where only the newest score matters.

You should use "a" for things like activity logs or journals. If you are recording every time a user logs into a system, you definitely don't want to erase the history of previous logins every time a new person arrives!

Key takeaway

Use "w" to wipe a file clean and start over; use "a" to add data to the end of what is already there.