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

Writing raw bytes with fwrite

Writing raw bytes with fwrite

What you'll learn: How to save exact copies of data from your computer's memory directly into a file without converting it to text.

Beyond Plain Text

Up until now, you have likely used fprintf to save data. When you use fprintf, C translates numbers into characters (like turning the number 100 into the characters '1', '0', '0'). This is great for humans to read, but inefficient for computers.

Think of Binary Writing like taking a snapshot of a drawer in your desk. Instead of writing a list describing every item in the drawer (text), you simply clone the entire drawer exactly as it is. In C, we use the fwrite function to perform this "memory dump."

How fwrite Works

The fwrite function doesn't care if you are saving integers, floats, or custom structures. It only cares about three things:

  1. Where is the data starting in memory?
  2. How big is each piece of data?
  3. How many pieces are there?

Here is how you save an array of integers directly to a file:

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    
    // Open the file in "wb" mode (write binary)
    FILE *file = fopen("data.bin", "wb");
    
    if (file != NULL) {
        // fwrite(pointer_to_data, size_of_element, count, file_pointer)
        fwrite(numbers, sizeof(int), 5, file);
        
        fclose(file);
    }
    
    return 0;
}

Breaking Down the Arguments

In the example above, fwrite takes four arguments:

  • numbers: The address of our data.
  • sizeof(int): We tell C that each "item" is the size of one integer (usually 4 bytes).
  • 5: We want to write five of those items.
  • file: The destination file.

Because we used "write binary" mode (wb), C copies the actual bits and bytes from your RAM into the file. If you try to open data.bin in a normal text editor like Notepad, it will look like gibberish. This is normal! The data is stored in a format meant for the computer to read back later, not for human eyes. This method is incredibly fast and keeps your files smaller than text-based alternatives.

Key takeaway

fwrite copies raw bytes directly from memory to a file, providing a fast and efficient way to store complex data exactly as the computer sees it.