Skip to content
StudyFame

Opening and Closing Files in C

Open a file with "w" and its old contents are wiped instantly. Open it with "a" and new text goes at the end. Open a missing file with "r" and you get NULL. The mode string you pass to fopen decides all of this.

In this lesson you will learn all the fopen modes (r, w, a, r+, w+, a+ and their binary versions), see exactly what each does, and learn to close files correctly. Mode questions appear in nearly every C exam.

What You Will Learn

  • The syntax of fopen and fclose.
  • The three basic modes: r, w, a.
  • The update modes: r+, w+, a+.
  • Binary modes with b.
  • What happens when the file does or doesn't exist.
  • Why and how to close files.

Opening and Closing Files Explained

Exam definition: fopen(filename, mode) opens a file in the given mode and returns a FILE *, or NULL on failure. The mode tells whether the file is opened for reading, writing (truncating), or appending, and whether updating (+) or binary (b) access is used. fclose(fp) closes the file and returns 0 on success.

Memory trick: r = read a book from the library (it must exist). w = a whiteboard: wipe it, then write. a = attendance register: add new lines at the end, never erase. + = "also the other one" (read and write).

Syntax of fopen() and fclose()

FILE *fopen(const char *filename, const char *mode);
int   fclose(FILE *fp);               /* 0 = success, EOF = error */

FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { /* not found / no permission */ }
fclose(fp);

fopen Modes Table

ModePurposeIf file existsIf file doesn't existPosition
"r"Read onlyOpens itReturns NULLStart
"w"Write onlyErases contentsCreates itStart
"a"Append onlyKeeps contentsCreates itAlways writes at end
"r+"Read and writeOpens it (no erase)Returns NULLStart
"w+"Write and readErases contentsCreates itStart
"a+"Read and appendKeeps contentsCreates itReads anywhere, writes at end
  • Add b for binary files: "rb", "wb", "ab", "rb+" (or "r+b"), "wb+", "ab+".
  • On Linux/macOS, text and binary modes behave the same. On Windows, text mode converts \n to \r\n, so use b for binary data.
  • C11 also adds "x" (e.g. "wx"): create a new file, but fail if it already exists, so nothing is overwritten by accident.

Example 1: w vs a (Overwrite vs Append)

#include <stdio.h>

void show(const char *name)
{
    char line[80];
    FILE *fp = fopen(name, "r");
    if (fp == NULL)
    {
        printf("  (cannot open %s)\n", name);
        return;
    }
    while (fgets(line, sizeof(line), fp) != NULL)
        printf("  %s", line);
    fclose(fp);
}

int main(void)
{
    FILE *fp;

    fp = fopen("log.txt", "w");          /* create */
    fprintf(fp, "Day 1: learnt variables\n");
    fclose(fp);

    fp = fopen("log.txt", "a");          /* add at the end */
    fprintf(fp, "Day 2: learnt loops\n");
    fclose(fp);
    printf("After w then a:\n");
    show("log.txt");

    fp = fopen("log.txt", "w");          /* wipe and write */
    fprintf(fp, "Day 3: learnt pointers\n");
    fclose(fp);
    printf("After w again:\n");
    show("log.txt");

    remove("log.txt");
    printf("Opening a missing file with r:\n");
    show("log.txt");

    return 0;
}

Output

After w then a:
  Day 1: learnt variables
  Day 2: learnt loops
After w again:
  Day 3: learnt pointers
Opening a missing file with r:
  (cannot open log.txt)

Code Explanation

  1. "w" creates log.txt and writes Day 1.
  2. "a" keeps Day 1 and adds Day 2 at the end.
  3. Opening with "w" again erases everything: only Day 3 remains. This is the most common file-handling accident.
  4. After remove, opening with "r" fails, so fopen returns NULL and show prints a message instead of crashing.

How the + Modes Work

The + modes allow both reading and writing on the same FILE pointer. One rule: when you switch between reading and writing, call a positioning function (fseek, rewind) or fflush in between.

"r+"  file must exist; read and overwrite from the start; nothing erased
"w+"  file emptied (or created); write first, rewind, then read
"a+"  file kept (or created); read from anywhere, but every write goes to the end

Example 2: Using w+ and r+ (Read and Write on One Pointer)

#include <stdio.h>

int main(void)
{
    FILE *fp;
    char word[20];
    int score;

    fp = fopen("score.txt", "w+");       /* create, then read back */
    if (fp == NULL)
        return 1;
    fprintf(fp, "Score 040\n");
    rewind(fp);                          /* go back before reading */
    fscanf(fp, "%19s %d", word, &score);
    printf("w+ wrote and read: %s %d\n", word, score);
    fclose(fp);

    fp = fopen("score.txt", "r+");       /* open existing, update in place */
    if (fp == NULL)
        return 1;
    fseek(fp, 6, SEEK_SET);              /* jump to the digits */
    fprintf(fp, "095");                  /* overwrite 3 characters */
    rewind(fp);
    fscanf(fp, "%19s %d", word, &score);
    printf("r+ updated to    : %s %d\n", word, score);
    fclose(fp);

    remove("score.txt");
    return 0;
}

Output

w+ wrote and read: Score 40
r+ updated to    : Score 95
  • w+ lets us write and then read back, after rewind moves the position to the start.
  • r+ opens the existing file without erasing it, so we can change just part of it.
  • fseek(fp, 6, SEEK_SET) moves to byte 6 (the "040"). Random access is covered in a later lesson.

Closing Files: fclose and fcloseall

  • fclose(fp) writes any buffered data, frees the FILE structure and releases the file for other programs.
  • It returns 0 on success and EOF on error (for example, the disk is full).
  • Don't use fp after closing it, and don't close the same pointer twice.
  • All open files are closed automatically when main returns normally, but closing them yourself is good practice. (fcloseall() exists only in some compilers, so avoid it.)

Important Points to Remember

  • r: read, file must exist.
  • w: write, erases or creates.
  • a: append at the end, keeps contents or creates.
  • + adds the other operation (read and write).
  • b = binary mode: rb, wb, ab…
  • Between reading and writing in + modes, use fseek/rewind/fflush.
  • fclose returns 0 on success; always close.

Common Mistakes Beginners Make

MistakeWhat happensFix
Using "w" to add recordsOld records erasedUse "a"
Using "r+" on a new filefopen returns NULLUse "w+" or "a+"
Mode as a char: fopen("f.txt", 'r')Compile error/crashMode is a string: "r"
Reading right after writing in w+Reads nothing (position at end)rewind(fp) first
Text mode for binary data on WindowsCorrupted bytesUse "rb" / "wb"

File Modes Practice Questions

  1. What is the difference between "w" and "a"?
  2. What is the difference between "r+" and "w+"?
  3. Which modes return NULL if the file doesn't exist?
  4. Which mode would you use to add a new log entry every day?
  5. Write the mode to open an existing binary file for reading and writing.
Show answers
  1. "w" erases the file (or creates it) and writes from the start; "a" keeps the contents and writes at the end.
  2. Both read and write; "r+" needs an existing file and keeps its contents; "w+" creates or erases the file.
  3. "r" and "r+" (and their binary versions).
  4. "a" (append).
  5. "rb+" (or "r+b").

Coding Exercise

Using "a" mode, append three expenses ("Tea 20", "Bus 35", "Lunch 120") to expenses.txt one at a time (open, write, close each time). Then read the file and print the total.

Show solution
#include <stdio.h>

void add(const char *item, int amount)
{
    FILE *fp = fopen("expenses.txt", "a");
    if (fp == NULL)
        return;
    fprintf(fp, "%s %d\n", item, amount);
    fclose(fp);
}

int main(void)
{
    FILE *fp;
    char item[20];
    int amount, total = 0;

    remove("expenses.txt");          /* start fresh for the demo */
    add("Tea", 20);
    add("Bus", 35);
    add("Lunch", 120);

    fp = fopen("expenses.txt", "r");
    if (fp == NULL)
        return 1;
    while (fscanf(fp, "%19s %d", item, &amount) == 2)
        total += amount;
    fclose(fp);

    printf("Total spent: Rs %d\n", total);
    remove("expenses.txt");
    return 0;
}
Total spent: Rs 175

Quick Quiz: fopen() File Modes (MCQ)

  1. Which mode erases an existing file?

    A) "r"   B) "a"   C) "w"   D) "r+"

  2. Mode to add data at the end without erasing:

    A) "w"   B) "a"   C) "r"   D) "w+"

  3. fopen("missing.txt", "r") returns:

    A) A new file   B) NULL   C) EOF   D) 0 bytes

  4. Mode to read and write an existing file without erasing it:

    A) "w+"   B) "r+"   C) "a"   D) "w"

  5. fclose returns on success:

    A) 1   B) 0   C) EOF   D) NULL

Show answers
  1. C: "w".
  2. B: "a".
  3. B: NULL.
  4. B: "r+".
  5. B: 0.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

"r"Read; file must exist
"w"Write; erases or creates
"a"Append at end; keeps or creates
"r+"Read + write, must exist, no erase
"w+"Write + read, erases or creates
"a+"Read + append, writes at end
"b"Binary version (rb, wb, ab)

Frequently asked questions

What is the difference between w and a mode?
w erases the file and writes from the start; a keeps the contents and writes at the end.
What is the difference between r+ and w+?
r+ needs an existing file and keeps it; w+ creates or erases the file.
What does fopen return if it fails?
NULL, so always check it before using the pointer.

Remember

  • r = library book, w = whiteboard, a = attendance register.
  • + = also the other job.

Next Topic

Next lesson: Reading and Writing Text Files. You will read and write text files with fprintf, fscanf, fgets, fputs, fgetc and fputc.