When a program stores structures, such as student records, converting every field to text is slow and awkward. fwrite and fread copy whole blocks of memory to and from a file in one call.
fwrite and fread
Prototypes Copy size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
size_t fread(void *ptr, size_t size, size_t count, FILE *fp);
Parameter Meaning ptrAddress of the data to write, or of the memory that will receive the data read sizeSize in bytes of one item , normally sizeof the variable or type countNumber of items to transfer fpThe file, normally opened in binary mode ("wb", "rb", "r+b")
Both return the number of items (not bytes) transferred. A return value smaller than count means the end of the file was reached or an error occurred, so while (fread(&rec, sizeof rec, 1, fp) == 1) reads records until the end.
Intuition
fprintf is like dictating a form aloud and having someone write it down field by field. fwrite is a photocopier: it copies the whole page (the bytes of the structure) exactly, without understanding it.
Correction · Prototypes and meaning of fread and fwrite
Study material says: in §8.3.4, int fread(void *buf, int num_bytes, int count, FILE *fp); (and the same for fwrite), with “num_bytes specifies the number of bytes to be read or written”.
Correct version: the parameter types and return type are size_t, the second argument is the size of one item , the third is the number of items, so the total bytes transferred are size × count, and the functions return the number of complete items transferred. In fwrite the first parameter is const void *.
Why: ISO C §7.21.8.1 and §7.21.8.2. For example, fwrite(s, sizeof(struct stud), 30, fp) writes 30 items of 40 bytes each, 1200 bytes in total, and returns 30 when it succeeds.
Example 8.11 Creating and reading a file of student records
Goal. Read three student records from the keyboard, store them in a binary file with one fwrite, then read them back one at a time with fread.
Step. Define the structure and read each record with scanf, passing & for the integer members.
Step. Open stud.dat with "wb", write the whole array, and close it.
Step. Reopen with "rb" and read while fread returns 1.
C · student_records.c Copy #include <stdio.h>
#include <stdlib.h>
#define N 3
struct stud {
char name[ 30 ];
int age;
int roll_no;
};
int main( void )
{
struct stud s[N], st;
FILE * fp;
size_t written;
int i;
printf( "Enter name, age and roll number of %d students: \n " , N);
for (i = 0 ; i < N; i ++ )
scanf( "%29s %d %d" , s[i].name, & s[i].age, & s[i].roll_no);
if ((fp = fopen( "stud.dat" , "wb" )) == NULL ) {
perror( "stud.dat" );
exit(EXIT_FAILURE);
}
written = fwrite(s, sizeof ( struct stud), N, fp);
fclose(fp);
printf( "%zu records (%zu bytes) written \n " , written, written * sizeof ( struct stud));
if ((fp = fopen( "stud.dat" , "rb" )) == NULL ) {
perror( "stud.dat" );
exit(EXIT_FAILURE);
}
while (fread( & st, sizeof st, 1 , fp) == 1 )
printf( "%-10s %3d %5d \n " , st.name, st.age, st.roll_no);
fclose(fp);
return 0 ;
}
Output Copy Enter name, age and roll number of 3 students:
Geeta 18 101
Leena 17 102
Mahesh 23 103
3 records (120 bytes) written
Geeta 18 101
Leena 17 102
Mahesh 23 103
Step. Check the size: each record is 30 + 4 + 4 = 38 bytes of members, rounded up to 40 so the int members are properly aligned (Unit 6), and 3 × 40 = 120.
Result. The array goes to disk in one call and comes back one record at a time, each record exactly once.
Correction · Errors in Example 8.4
Study material says: Example 8.4 reads with scanf("%s %d %d", s[i].name, s[i].age, s[i].roll_no);, writes to "sud.dat" but reopens "stud.dat", opens both with text modes "w" and "r", prints with fprintf("%s %d %d", st.name, …), loops with while (!feof(fp)), and says the program “writes one record at a time to a file”.
Correct version: pass addresses (&s[i].age, &s[i].roll_no); use one file name; open with "wb" and "rb"; print with printf (or fprintf(stdout, …)); loop with while (fread(&st, sizeof st, 1, fp) == 1). The single fwrite call writes all 30 records at once, as in the program above.
Why: scanf needs addresses to store values; gcc warns “format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’”. The second fopen fails because stud.dat was never created. fprintf needs a file pointer first. With the feof loop, the last record is printed twice: a test with two records printed the second one again.
Key idea
fwrite(ptr, sizeof item, count, fp) copies memory to a binary file and fread copies it back; both return the number of items transferred, so read with while (fread(&rec, sizeof rec, 1, fp) == 1).
TEE Exam note
“What is the advantage of using fread/fwrite?” (Check Your Progress 2, question 2): they transfer whole blocks (a record, an array of records) in one call with no conversion between numbers and text, so they are fast and simple for storing structures, and every record has a fixed size, which makes random access possible. Be ready to write the program that creates and reads a file of student records.
Common mistake
Reading records with a feof loop, which processes the last record twice.
Key takeaways
fwrite and fread transfer count items of size bytes each.
They return the number of complete items transferred.
Use binary modes ("wb", "rb", "r+b") for record files.
Read records with while (fread(...) == 1).
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice What does fwrite(arr, sizeof(int), 10, fp) write on success?
A 10 bytes B One int C 10 integers, that is 10 × sizeof(int) bytes D The address of arr
Check answer
Show answer Answer: C. 10 integers, that is 10 × sizeof(int) bytes
The second argument is the size of one item and the third the number of items; with a 4-byte int this is 40 bytes.
Question 2 · multiple choice A The number of bytes read B The number of complete items read C EOF at the end of the fileD A pointer to the data
Check answer
Show answer Answer: B. The number of complete items read
Like fwrite, it counts items. At the end of the file it returns fewer items than requested (often 0), not EOF.
Question 3 · multiple choice Which mode should be used to create a new file of structure records?
A "r"B "w"C "a"D "wb"
Check answer
Show answer Answer: D. "wb"
w creates (or empties) the file, and b selects binary mode, which stores the bytes without any newline translation.
Question 4 · multiple choice A file contains exactly 4 records of type struct item. What does this fragment print?
C · count_records.c Copy #include <stdio.h>
struct item { int code; double price; };
int main( void )
{
struct item it[ 4 ] = {{ 1 , 2.5 }, { 2 , 3.0 }, { 3 , 1.5 }, { 4 , 9.0 }}, x;
FILE * fp = fopen( "items.dat" , "wb" );
int n = 0 ;
if (fp == NULL )
return 1 ;
fwrite(it, sizeof it[ 0 ], 4 , fp);
fclose(fp);
fp = fopen( "items.dat" , "rb" );
if (fp == NULL )
return 1 ;
while (fread( & x, sizeof x, 1 , fp) == 1 )
n ++ ;
fclose(fp);
printf( "%d \n " , n);
return 0 ;
} A 5 B 3 C 0 D 4
Check answer
Show answer Answer: D. 4
Four records are written in one call and the loop reads each once; the fifth fread returns 0 and ends the loop.
Question 5 · multiple choice Why are fixed-size binary records convenient?
A They can be opened in any text editor B Record n starts at byte n × sizeof(record), so it can be reached directly C They take less space than text for every value D They are portable to every machine
Check answer
Show answer Answer: B. Record n starts at byte n × sizeof(record), so it can be reached directly
Fixed sizes make positions predictable, which is the basis of random access with fseek. Binary files are not readable in editors and not always portable.
Question 6 · short answer
Write statements that save an int array marks[50] to marks.dat in one call and check that the whole array was written.
Show worked answer FILE *fp = fopen("marks.dat", "wb"); if (fp == NULL) { perror("marks.dat"); return 1; } if (fwrite(marks, sizeof marks[0], 50, fp) != 50) printf("Write error\n"); fclose(fp);. sizeof marks[0] is the size of one int, 50 is the number of items, and comparing the return value with 50 confirms that every item reached the file.