About GBdirect Consultancy Training Development

Section navigation

Leeds Office (National HQ)

GBdirect Ltd
Leeds Innovation Centre
103 Clarendon Road
LEEDS
LS2 9DF
West Yorkshire
United Kingdom

consulting@gbdirect.co.uk

tel: +44 (0)870 200 7273
Sales: 0800 651 0338

South East Regional Office

GBdirect Ltd
18 Lynn Rd
ELY
CB6 1DA
Cambridgeshire
United Kingdom

consulting@gbdirect.co.uk

tel: +44 (0)870 200 7273
Sales: 0800 651 0338

Please note: Initial enquiries should always be directed to our UK national office in Leeds (West Yorkshire), even if the enquiry concerns services delivered in London or South/East England. Clients in London and the South East will typically be handled by staff working in the London or Cambridge areas.

9.13. Unformatted I/O

This is simple: only two functions provide this facility, one for reading and one for writing:

#include <stdio.h>

size_t fread(void *ptr, size_t size, size_t nelem, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nelem, FILE *stream);

In each case, the appropriate read or write is performed on the data pointed to by ptr. Up to nelem elements, of size size, are transferred. Failure to transfer the full number is an error only when writing; End of File can prevent the full number on input. The number of elements actually transferred is returned. To distinguish between End of File on input, or an error, use feof or ferror.

If size or nelem is zero, fread does nothing except to return zero.

An example may help.

#include <stdio.h>
#include <stdlib.h>

struct xx{
        int xx_int;
        float xx_float;
}ar[20];

main(){

        FILE *fp = fopen("testfile", "w");

        if(fwrite((const void *)ar,
                sizeof(ar[0]), 5, fp) != 5){

                fprintf(stderr,"Error writing\n");
                exit(EXIT_FAILURE);
        }

        rewind(fp);

        if(fread((void *)&ar[10],
                sizeof(ar[0]), 5, fp) != 5){

                if(ferror(fp)){
                        fprintf(stderr,"Error reading\n");
                        exit(EXIT_FAILURE);
                }
                if(feof(fp)){
                        fprintf(stderr,"End of File\n");
                        exit(EXIT_FAILURE);
                }
        }
        exit(EXIT_SUCCESS);
}
Example 9.7