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

Understanding file modes: r, w, a

Understanding file modes: r, w, a

What you'll learn: You will learn how to use file modes to tell C whether you want to read, overwrite, or add data to a file.

Choosing Your Permission

When you use the fopen() function in C, you aren't just telling the computer which file to open; you are telling it how you intend to use it. This is done via a "mode" string. Think of it like a safety permit: you wouldn't want to accidentally scribble over your favorite book when you only meant to read it.

C uses three primary modes to manage these permissions: r, w, and a.

The Three Modes

1. Read Mode ("r")

This is the "look but don't touch" mode. Use this when you want to pull information out of an existing file.

  • Behavior: It starts at the very beginning of the file.
  • Safety Catch: If the file doesn't exist, fopen() will return NULL. It won't create a new file for you because you can't read something that isn't there!

2. Write Mode ("w")

Think of this as the "fresh start" mode. Use this when you want to create a new file or completely replace an old one.

  • Behavior: If the file already exists, C erases everything inside it the moment you open it. If the file doesn't exist, C creates a brand-new blank file for you.
  • Analogy: It’s like clearing a whiteboard before you start drawing.

3. Append Mode ("a")

This is the "keep it going" mode. Use this when you want to add new data to the end of a file without touching what is already there.

  • Behavior: It ignores the beginning and jumps straight to the end of the file. If the file doesn't exist, it creates a new one.
  • Analogy: Like adding a new line to a grocery list.

How it looks in code

#include <stdio.h>

int main() {
    // 1. Open for reading
    FILE *readPtr = fopen("notes.txt", "r");

    // 2. Open for writing (Warning: this wipes notes.txt if it exists!)
    FILE *writePtr = fopen("notes.txt", "w");

    // 3. Open for appending (Safely adds to the end)
    FILE *appendPtr = fopen("notes.txt", "a");

    // Always close your files when done
    if(readPtr) fclose(readPtr);
    if(writePtr) fclose(writePtr);
    if(appendPtr) fclose(appendPtr);

    return 0;
}

Key takeaway

Use "r" to extract data, "w" to create or overwrite a file, and "a" to add data to the end of an existing file.