9.13. Unformatted I/OThis 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 If 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 BookThis 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
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday South East Regional Office
GBdirect Ltd
Training: 0800 651 0338 Please call between 0900 and 1700 (UK time) on Monday to Friday Please note: |