What is fwrite in C Explained- Online Embedded C Programming Classes

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free Embedded C Course | Chapter 11: Files

fwrite in C Explained

Learn every common way to call fwrite(), how to read its return value, and how to write a record file for embedded data logging.

This lecture of our free embedded C course is about fwrite in C, the function that dumps blocks of memory into a file. If you plan to log sensor samples, save settings or store firmware records, fwrite() is the workhorse. We cover its parameters, five real calling patterns with measured output, the size and count trap, and a complete record logger. This is a free C programming course lecture written for students who build real devices.

What You Will Learn

  • What fwrite() does with ptr, size, nmemb and stream
  • Five calling patterns: variable, whole array, partial array, structure, structure array
  • How to read the return value and detect write failures
  • Why sizeof beats typed numbers
  • How to write and inspect a record file with od

Prerequisites

  • Binary block I/O lecture (cp11_19)
  • Structures and fixed-width types from stdint.h
  • Using the od command

How fwrite in C Works

fwrite() takes a memory address, reads size * nmemb bytes starting there, and appends them to the stream. It does not look at the type of the data. A float, a structure and an array of structures are all just bytes to it.

fwrite data flow
ptr in RAM→size x nmemb bytes→stream buffer→file
Returns→items fully written

Note: The return value counts items, not bytes. A full success returns exactly nmemb.

Five Ways to Call fwrite

The program below writes five different shapes of data into one file and prints the return value plus the file position after each call. The position tells you how many bytes were stored so far.

#include <stdio.h>
#include <stdint.h>

struct sample {
    char     tag[8];
    uint16_t id;
    float    reading;
};

static long file_size(FILE *fp)
{
    long pos = ftell(fp);
    return pos;
}

int main(void)
{
    FILE *fp = fopen("forms.bin", "wb");
    float temp = 36.5f;
    int   codes[6] = {10, 20, 30, 40, 50, 60};
    struct sample one = {"S1", 101, 2.5f};
    struct sample batch[4] = {
        {"A", 1, 1.1f}, {"B", 2, 2.2f}, {"C", 3, 3.3f}, {"D", 4, 4.4f}
    };
    size_t n;

    if (fp == NULL) {
        perror("forms.bin");
        return 1;
    }

    printf("sizeof(struct sample) = %zu\n\n", sizeof(struct sample));

    n = fwrite(&temp, sizeof temp, 1, fp);
    printf("single float      : returned %zu, file at %ld bytes\n", n, file_size(fp));

    n = fwrite(codes, sizeof(int), 6, fp);
    printf("whole int array   : returned %zu, file at %ld bytes\n", n, file_size(fp));

    n = fwrite(codes, sizeof(int), 3, fp);
    printf("first 3 ints      : returned %zu, file at %ld bytes\n", n, file_size(fp));

    n = fwrite(&one, sizeof one, 1, fp);
    printf("one struct        : returned %zu, file at %ld bytes\n", n, file_size(fp));

    n = fwrite(batch, sizeof batch[0], 2, fp);
    printf("2 of 4 structs    : returned %zu, file at %ld bytes\n", n, file_size(fp));

    fclose(fp);
    return 0;
}
gcc -Wall -Wextra -std=c11 -o ep_fwrite_forms ep_fwrite_forms.c
./ep_fwrite_forms
sizeof(struct sample) = 16

single float      : returned 1, file at 4 bytes
whole int array   : returned 6, file at 28 bytes
first 3 ints      : returned 3, file at 40 bytes
one struct        : returned 1, file at 56 bytes
2 of 4 structs    : returned 2, file at 88 bytes
GoalCall patternBytes written
One variablefwrite(&temp, sizeof temp, 1, fp)4
Whole arrayfwrite(codes, sizeof(int), 6, fp)24
First part of an arrayfwrite(codes, sizeof(int), 3, fp)12
One structurefwrite(&one, sizeof one, 1, fp)16
Part of a structure arrayfwrite(batch, sizeof batch[0], 2, fp)32

Notice the structure is 16 bytes even though its fields add up to 14: the compiler inserted 2 padding bytes after the 16-bit field so the float is aligned. We study this in the lab lecture.

Why Use sizeof Instead of Typed Numbers

If you write 4 as the item size and later change the field from float to double, the file silently becomes wrong. sizeof is evaluated by the compiler, so it follows every change to the type and also adapts when you recompile for another target.

Size and Count Are Not Interchangeable

Both calls below move the same 40 bytes, yet they report different results.

#include <stdio.h>

int main(void)
{
    int data[10] = {1,2,3,4,5,6,7,8,9,10};
    FILE *fp = fopen("swap.bin", "wb");
    size_t a, b;

    if (fp == NULL) {
        perror("swap.bin");
        return 1;
    }
    /* Same 40 bytes, two different return values */
    a = fwrite(data, sizeof(int), 10, fp);   /* 10 items of 4 bytes */
    b = fwrite(data, 10 * sizeof(int), 1, fp); /* 1 item of 40 bytes */
    printf("size=4, n=10 returned %zu\n", a);
    printf("size=40, n=1 returned %zu\n", b);
    fclose(fp);
    return 0;
}
size=4, n=10 returned 10
size=40, n=1 returned 1

Use the real item size and the real count. Then the return value tells you how many items survived a failure instead of just yes or no.

Writing a Record File Step by Step

Here is a tiny logger format: sequence number, temperature times ten, and a raw ADC value. Fixed-width types keep the size predictable.

#ifndef EP_RECORDS_H
#define EP_RECORDS_H
#include <stdint.h>

struct log_rec {
    uint32_t seq;
    int16_t  temp_c10;   /* temperature x10 */
    uint16_t adc;
};
#endif
#include <stdio.h>
#include "ep_records.h"

int main(void)
{
    struct log_rec recs[5] = {
        {1, 245, 1020}, {2, 247, 1031}, {3, 251, 1044},
        {4, 249, 1038}, {5, 256, 1060}
    };
    FILE *fp = fopen("log.bin", "wb");
    size_t done;

    if (fp == NULL) {
        perror("log.bin");
        return 1;
    }
    done = fwrite(recs, sizeof recs[0], 5, fp);
    if (done != 5)
        fprintf(stderr, "short write: %zu of 5\n", done);
    if (fclose(fp) != 0) {
        perror("fclose");
        return 1;
    }
    printf("wrote %zu records, %zu bytes each\n", done, sizeof(struct log_rec));
    return 0;
}
gcc -Wall -Wextra -std=c11 -o ep_rec_write ep_rec_write.c
./ep_rec_write
od -An -tx1 -w8 log.bin
wrote 5 records, 8 bytes each
 01 00 00 00 f5 00 fc 03
 02 00 00 00 f7 00 07 04
 03 00 00 00 fb 00 14 04
 04 00 00 00 f9 00 0e 04
 05 00 00 00 00 01 24 04
Bytes in record 1FieldDecoded value
01 00 00 00seq (uint32_t, little-endian)1
f5 00temp_c10 (int16_t)245, meaning 24.5 C
fc 03adc (uint16_t)1020
Layout of one log_rec
seq: bytes 0-3temp_c10: bytes 4-5adc: bytes 6-7

Five records of 8 bytes make a 40-byte file, which you can confirm with ls -l log.bin.

Common fwrite Mistakes and Troubleshooting

MistakeSymptomFix
sizeof(pointer) used as the data sizeFile has only 8 bytesPass element size and count
Writing the whole array when only part is filledGarbage records in the fileWrite only the filled count
Opening with “w” instead of “wb”Corrupt bytes on WindowsUse “wb”
Never checking fclose()Disk full goes unnoticedTest the fclose() result
Structure with pointer membersMeaningless addresses savedStore the data, not the address

Best Practices, Performance and Security

  • Always compare the fwrite() result with the count you requested.
  • Write many records per call: one fwrite() of 100 records beats 100 calls of one record.
  • Call fflush() or fclose() before assuming the data is stored, especially before power may be lost.
  • Do not store secrets such as keys in plain binary files.
  • Zero a structure with memset() or an initializer before writing so padding bytes do not leak old stack contents.

Summary and Key Takeaways

  • fwrite(ptr, size, nmemb, fp) writes size times nmemb bytes and returns whole items written.
  • Use sizeof for the item size and the real filled count for nmemb.
  • Never use sizeof(pointer) as the data size.
  • Check both the fwrite() result and the fclose() result.
  • Inspect files with od -An -tx1 to see exactly what was stored.

Conclusion

You can now save any block of memory to a file and prove what was written. In the next lecture we do the reverse with fread(), including how to detect a damaged file and how reading records one by one differs from jumping straight to a record.

Frequently Asked Questions

What does fwrite return?

It returns the number of complete items it wrote. If that is less than the count you asked for, a write error occurred and you should inspect ferror() and errno.

Should I use sizeof(array) or sizeof(element) in fwrite?

Pick the form that matches how you split size and count. fwrite(arr, sizeof arr[0], count, fp) is the safest habit because the return value then counts elements.

Why does fwrite(ptr, sizeof(ptr), 1, fp) write only 8 bytes?

sizeof(ptr) is the size of the pointer itself, usually 8 bytes on 64-bit systems, not the data it points to. Pass the element size and element count explicitly.

Can I write a structure that contains pointers?

You can, but the file will store the address values, which are meaningless the next time the program runs. Store the pointed-to data instead.

Does fwrite put data on disk immediately?

No. It copies into the stream buffer. The data reaches the file when the buffer fills, when you call fflush(), or when fclose() succeeds. Check fclose() for errors too.

What happens if I write a partly filled array?

If you write the full array, the unused elements contain garbage that ends up in the file. Write only the count you actually filled.

Continue Free C Programming

Next up: fread() in depth, end-of-file handling and a preview of random access.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →