| Types and objects | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <stdio.h> | ||
| (until C99) | ||
| (since C99) | ||
Reads up tocount objects into the arraybuffer from the given input streamstream as if by callingfgetcsize times for each object, and storing the results, in the order obtained, into the successive positions ofbuffer, which is reinterpreted as an array ofunsignedchar. The file position indicator for the stream is advanced by the number of characters read.
If an error occurs, the resulting value of the file position indicator for the stream isindeterminate. If a partial element is read, its value is indeterminate.
Contents |
| buffer | - | pointer to the array where the read objects are stored |
| size | - | size of each object in bytes |
| count | - | the number of the objects to be read |
| stream | - | the stream to read |
Number of objects read successfully, which may be less thancount if an error or end-of-file condition occurs.
Ifsize orcount is zero,fread returns zero and performs no other action.
fread does not distinguish between end-of-file and error, and callers must usefeof andferror to determine which occurred.
#include <stdio.h> enum{ SIZE=5}; int main(void){constdouble a[SIZE]={1.0,2.0,3.0,4.0,5.0};printf("Array has size %ld bytes, element size: %ld\n",sizeof a,sizeof*a);FILE*fp=fopen("test.bin","wb");// must use binary modefwrite(a,sizeof*a, SIZE, fp);// writes an array of doublesfclose(fp); double b[SIZE]; fp=fopen("test.bin","rb");constsize_t ret_code= fread(b,sizeof b[0], SIZE, fp);// reads an array of doublesif(ret_code== SIZE){printf("Array at %p read successfully, contents:\n",(void*)&a);for(int n=0; n!= SIZE;++n)printf("%f ", b[n]);putchar('\n');}else// error handling{if(feof(fp))printf("Error reading test.bin: unexpected end of file\n");elseif(ferror(fp))perror("Error reading test.bin");} fclose(fp);}
Possible output:
Array has size 40 bytes, element size: 8Array at 0x1337f00d6960 read successfully, contents:1.000000 2.000000 3.000000 4.000000 5.000000
(C11)(C11)(C11) | reads formatted input fromstdin, a file stream or a buffer (function)[edit] |
| gets a character string from a file stream (function)[edit] | |
| writes to a file (function)[edit] | |
C++ documentation forfread | |