Site Sections => About Us | Consultancy | Training | Software | Publications | Open Source | Support | Open Standards | FAQ | Jobs
Site Style Info

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

The C Book

This book is published as a matter of historical interest. Please read the copyright and disclaimer information.

GBdirect Ltd provides up-to-date training and consultancy in C, Embedded C, C++ and a wide range of other subjects based on open standards if you happen to be interested.


West Yorkshire Office

GBdirect Ltd
Bradford Design Exchange
34 Peckover Street
BRADFORD
BD1 5BD
West Yorkshire
United Kingdom

consulting@gbdirect.co.uk

Training: 0800 651 0338
General: +44 (0)870 200 7273
Finance: +44 (0)1353 615 174

Please call between 0900 and 1700 (UK time) on Monday to Friday


South East Regional Office

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

consulting@gbdirect.co.uk

Training: 0800 651 0338
General: +44 (0)870 200 7273
Finance: +44 (0)1353 615 174

Please call between 0900 and 1700 (UK time) on Monday to Friday


Please note:
Non-training enquiries should be directed, initially, to our UK national office in Bradford (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.