CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Reading and writing binary data structures

The fread() function reads an indicated number of elements, each of which is the same size:

    size_t  fread(void *ptr, size_t eachsize, size_t nelem, FILE *stream);

This mechanism enables our programs to read arbitrary sized data, by setting eachsize to one (a single byte), or to read a known number of data items each of the same size:


#include <stdio.h>

int   intarray[ N_ELEMENTS ];
int   got, wrote;

//  OPEN THE BINARY FILE FOR READING AND WRITING
    FILE  *fp = fopen(filename, "rb+");
    ....

    got = fread( intarray, sizeof int, N_ELEMENTS, fp);  
    printf("just read in %i ints\n", got);

//  MODIFY THE BINARY DATA IN THE ARRAY
    ....

//  REWIND THE FILE TO ITS BEGINNING
    rewind(fp);

//  AND NOW OVER-WRITE THE BEGINNING DATA
    wrote = fwrite( intarray, sizeof int, N_ELEMENTS, fp);  
    ....

    fclose(fp);

 


CITS2002 Systems Programming, Lecture 8, p14, 15th August 2023.