CS 3 (Spring 2024) fread, fwrite

Name

fread, fwrite - binary stream input/output

Synopsis

#include <stdio.h>

size_t fread(void *data, size_t size, size_t count, FILE *stream);
size_t fwrite(const void *data, size_t size, size_t count, FILE *stream);

Description

fread() reads count elements, each size bytes long, from stream, writing them to the location given by data.

fwrite() writes count elements, each size bytes long, to stream, reading them from the location given by data.

If stream is a file stream, fread() and fwrite() update its current position in the file, advancing past the items that were read or written.

The number of bytes read or written is count * size; only the return value depends on size by itself.

Example

#include <assert.h>
#include <stdio.h>

int main() {
    // Write a struct and a string to a file
    FILE *file = fopen("hello.txt", "w");
    assert(file != NULL);
    size_t value = 0x12345678;
    size_t written = fwrite(&value, sizeof(size_t), 1, file);
    assert(written == 1);
    written = fwrite("abc", sizeof(char), 3, file);
    assert(written == 3);
    fclose(file);

    /* The contents of the file (notice the little-endian first 8 bytes):
    00000000: 78 56 34 12 00 00 00 00 61 62 63                 xV4.....abc
    */

    // Read the struct and string back from the file
    file = fopen("hello.txt", "r");
    assert(file != NULL);
    size_t read_value;
    size_t read = fread(&read_value, sizeof(size_t), 1, file);
    assert(read == 1);
    assert(read_value == 0x12345678);
    char chars[10];
    read = fread(chars, sizeof(char), 10, file);
    assert(read == 3); // only 3 characters remain to be read from the file
    assert(chars[0] == 'a' && chars[1] == 'b' && chars[2] == 'c');
    fclose(file);
}

Return Value

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

fread() does not distinguish between end-of-file and error, and callers must use feof() and ferror() to determine which occurred.

See Also

fopen(), fclose(), fflush(), fseek()