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

Text mode vs Binary mode (b flag)

Text mode vs Binary mode (b flag)

What you'll learn: How to tell C whether to interpret your file as readable sentences or raw data bits.

When you open a file in C using fopen(), you have to choose a mode. While you are likely familiar with "r" (read) and "w" (write), there is a crucial extra character you can add: the letter b. This distinguishes between Text mode (the default) and Binary mode (using the b flag).

The Translator vs. The Mover

Think of Text mode as having a helpful translator standing between your program and the hard drive. This translator looks for specific characters, like the "New Line" character (\n), and tries to make them look correct for your specific Operating System. For example, on Windows, a new line is actually two hidden characters combined. In Text mode, C automatically converts these for you so you only see \n.

Binary mode, on the other hand, is like a professional mover. It doesn't look at what is inside the boxes; it just moves them exactly as they are. If you open a file with "rb" (read binary) or "wb" (write binary), C will not change a single bit of your data.

Why use Binary mode?

If you are saving a simple list of names or a poem, Text mode is great. But what if you are saving an image, a sound file, or a collection of raw integers?

If you use Text mode for an image, the "translator" might see a random byte of data that looks like a new line character and try to "fix" it. This corrupts your file, making the image unreadable. Binary mode ensures that what you write to the disk is exactly what stays on the disk.

How to use the 'b' flag

You simply append b to your mode string. It can come after the main letter:

#include <stdio.h>

int main() {
    // Open a file for writing in BINARY mode
    FILE *filePtr = fopen("data.bin", "wb");

    if (filePtr != NULL) {
        int myData = 12345;
        
        // We use fwrite for binary instead of fprintf
        fwrite(&myData, sizeof(int), 1, filePtr);
        
        fclose(filePtr);
    }

    return 0;
}

In the example above, we use "wb". This tells C: "Open this file for writing, but don't touch or translate any of the bits I send you."

Key takeaway

Use Text mode ("r", "w") for human-readable words, and always use Binary mode ("rb", "wb") for raw data like images, audio, or custom struct data to prevent accidental corruption.