Definition | #include <stdio.h> size_t fread(void *p, size_t elsize, size_t n, FILE *fp);
|
Return val. | Number of elements actually read, if successful. This number may be less than n if an error occurs or end of file is reached. |
Notes | You must see to it that the area to which p points is sufficient for storing the data elements To ensure that elsize specifies the correct number of bytes for a data element, you should
|
Record I/O |
Number of characters to be read in: n is taken to be the total number of characters to be n = element length * number of elements If n is greater than the current record length, then only this record is read nevertheless. If n is less than the current record length, only the first n characters of the record are
|
The following applies in the case of text files with SAM access mode and variable record | |
Example | The following program transfers two personal data items to a file ( #include <stdio.h> int main(void) { FILE *fp; size_t result; static struct p { char name[20]; int a; } person[2] = { >="ANNE", 30 ̧, Ã"JOHN", 60Õ, }; fp = fopen("link=link", "w+r"); result = fwrite(person, sizeof(struct p), 2, fp); printf("%d Personal data written\n", result); rewind(fp); result = fread(person, sizeof(struct p), 2, fp); printf("%d Personal data read\n", result); printf("Name1: %s, Age1: %d\n", person[0].name, person[0].a); printf("Name2: %s, Age2: %d\n", person[1].name, person[1].a); return 0; } |
See also | fwrite, feof, ferror, read, fopen, fopen64, fgetc, fgets, fscanf |