In the previous tutorial, we saved student records to students.txt using fprintf() and loaded them using fscanf(). This lesson modifies that same parallel-array program to use a binary file. We will keep the menu, arrays, and record count, but change the file-handling functions.
Learning objectives
By the end of this lesson, you should be able to distinguish text files from binary files, use fopen() with "wb" and "rb", write values using fwrite(), read them using fread(), and explain why binary records must be read in the same order they were written.
1. What changes from the text-file program?
Our arrays stay the same: names[MAX][50], maths[MAX], english[MAX], and n. The menu still offers Add, Display, Save, and Exit. Only the file name and file-reading/writing code change.
- Change
students.txttostudents.dat. - Open the file using
"wb"to write binary data or"rb"to read it. - Replace
fprintf()withfwrite(). - Replace
fscanf()withfread(). - Keep the same order of fields when saving and loading.
2. Text files compared with binary files
In students.txt, the number 75 appears as the characters 7 and 5. A binary file stores the bytes of the C value itself. A text file is easy to inspect in a text editor; students.dat is not intended to be read as ordinary text. Both files store information after the program exits.
The new file is not interchangeable with the old text file. Running this program will not automatically convert students.txt. Keep the old file for comparison; the new program uses students.dat.
3. Understand fwrite() and fread()
fwrite(&n, sizeof(n), 1, fp);
fread(&count, sizeof(count), 1, fp);The arguments mean: address of the data, size of one item in bytes, number of items, and file pointer. The functions return the number of complete items written or read. A result of 1 means one requested item was processed successfully.
The & operator gives the address of an integer. For a character array such as names[i], the array name already refers to the beginning of its storage. sizeof(names[i]) is 50 bytes, so we save a fixed-length name field.
4. Save the student records as binary data
FILE *fp = fopen("students.dat", "wb");
fwrite(&n, sizeof(n), 1, fp);
for (int i = 0; i < n; i++) {
fwrite(names[i], sizeof(names[i]), 1, fp);
fwrite(&maths[i], sizeof(maths[i]), 1, fp);
fwrite(&english[i], sizeof(english[i]), 1, fp);
}
fclose(fp);The first value written is n, the number of students. The loop then writes each student’s 50-byte name field, Mathematics mark, and English mark. "wb" creates or overwrites the binary file. The complete program below also checks whether writes succeeded.
5. Load the student records
FILE *fp = fopen("students.dat", "rb");
if (fp == NULL) return;
int count;
if (fread(&count, sizeof(count), 1, fp) != 1) {
fclose(fp);
return;
}The program first tries to open the file. If it does not exist, it starts with zero students. Otherwise it reads the saved count and checks that the count is between 0 and MAX. It then reads the records in the exact same order used when saving. If the file ends unexpectedly, the program stops loading.
6. Understand the binary file layout
The file begins with the binary representation of the integer count. Each student then occupies 50 + sizeof(int) + sizeof(int) bytes: 50 bytes for the name, followed by two integer marks. For example, on a system where int occupies 4 bytes, that is 58 bytes per student. The count itself would occupy 4 bytes on that system.
This introductory file format is designed for the same program and computer environment. Binary integer size and byte order can differ between systems, so it is not a portable interchange format. We are also storing fixed-length, single-word names.
7. Complete modified C program
Create a new C source file in Code::Blocks. Compare the two versions, especially loadData() and saveData().
#include <stdio.h>
#define MAX 100
char names[MAX][50];
int maths[MAX], english[MAX];
int n = 0;
void loadData() {
FILE *fp = fopen("students.dat", "rb");
if (fp == NULL) return;
int count;
if (fread(&count, sizeof(count), 1, fp) != 1 ||
count < 0 || count > MAX) {
printf("Invalid or incomplete data file.\n");
fclose(fp);
return;
}
for (int i = 0; i < count; i++) {
if (fread(names[i], sizeof(names[i]), 1, fp) != 1 ||
fread(&maths[i], sizeof(maths[i]), 1, fp) != 1 ||
fread(&english[i], sizeof(english[i]), 1, fp) != 1) {
printf("Incomplete record in data file.\n");
n = i;
fclose(fp);
return;
}
names[i][49] = '\0';
n++;
}
fclose(fp);
}
void saveData() {
FILE *fp = fopen("students.dat", "wb");
if (fp == NULL) {
printf("Cannot open binary file for writing.\n");
return;
}
int ok = (fwrite(&n, sizeof(n), 1, fp) == 1);
for (int i = 0; i < n && ok; i++) {
if (fwrite(names[i], sizeof(names[i]), 1, fp) != 1 ||
fwrite(&maths[i], sizeof(maths[i]), 1, fp) != 1 ||
fwrite(&english[i], sizeof(english[i]), 1, fp) != 1)
ok = 0;
}
if (fclose(fp) != 0) ok = 0;
if (ok) printf("Binary data saved.\n");
else printf("Error while saving data.\n");
}
void addStudent() {
if (n >= MAX) {
printf("Arrays are full.\n");
return;
}
printf("Enter name (one word): ");
if (scanf("%49s", names[n]) != 1) return;
printf("Enter Maths mark: ");
if (scanf("%d", &maths[n]) != 1) return;
printf("Enter English mark: ");
if (scanf("%d", &english[n]) != 1) return;
n++;
}
void displayData() {
printf("\nName\tMaths\tEnglish\n");
for (int i = 0; i < n; i++)
printf("%s\t%d\t%d\n", names[i], maths[i], english[i]);
}
int main() {
int choice;
loadData();
do {
printf("\n1. Add Student\n2. Display Students\n3. Save Data\n4. Exit\nEnter choice: ");
if (scanf("%d", &choice) != 1) {
printf("Please enter a number.\n");
break;
}
switch (choice) {
case 1: addStudent(); break;
case 2: displayData(); break;
case 3: saveData(); break;
case 4: printf("Goodbye!\n"); break;
default: printf("Invalid choice.\n");
}
} while (choice != 4);
return 0;
}8. Practical activity
- Run the binary version. Add John (75, 80), Mary (90, 85), and Peter (65, 70). Select Display.
- Select Save. Find
students.datin the program’s working directory. Notice that it is not a readable list of names and marks in a text editor. - Exit and run the program again. Select Display and verify that the three records were loaded.
- Add Sarah (88, 92), save, restart, and confirm that all four records appear.
- Compare the text and binary programs: identify the file modes and the functions used to write and read.
9. Check your understanding
- Why do we use
"wb"instead of"w"when writing the binary file? - What is the purpose of
fwrite()? - What does
sizeof(maths[i])tell the program? - Why must
fread()use the same field order asfwrite()? - Why do we save
nbefore the student records? - What happens if
students.datdoes not exist when the program starts? - Why should you not expect to read
students.datas ordinary text? - Does this program automatically read the old
students.txtfile? Explain.
10. Programming challenges
- Modify the program so it saves automatically when the user selects Exit.
- Add a Computer Science mark to the parallel arrays and update both binary file functions.
- Display each student’s average mark without changing the file format.
- Investigate what happens when you try to load a damaged or incomplete
students.datfile. Make a backup first.
Summary
The student records are still held in parallel arrays while the program runs. The difference is how they are saved: fprintf() and fscanf() handle formatted text, whereas fwrite() and fread() handle bytes. Saving and loading must agree on the record layout.
© 2024 Vedesh Kungebeharry. All rights reserved.
