This lesson continues our binary-file student-records tutorial. Previously, we stored names, Mathematics marks, and English marks in three separate parallel arrays. We will now group the fields belonging to one student into a structure, then use an array of structures. The Add, Display, Save, and Exit menu stays familiar.
Learning objectives
By the end, you should be able to declare a struct, create an array of structures, access fields using the dot operator, compare structures with parallel arrays, and save and load an array of student structures using binary files.
1. Why use a structure?
With parallel arrays, the same student is stored at the same index in three places: names[i], maths[i], and english[i]. A structure groups these related fields into one record. This makes it easier to keep each student’s information together.
struct Student {
char name[50];
int maths;
int english;
};Here Student is the structure tag, and name, maths, and english are its members. The semicolon after the closing brace is required. This declaration describes a type; it does not yet create the 100 student records.
2. Create an array of structures
struct Student students[MAX];
int n = 0;Instead of three arrays, students is one array with up to MAX student records. students[0] represents the first student, students[1] the second, and so on. As before, n counts how many records are actually in use.
3. Access members using the dot operator
students[0].maths = 75;
students[0].english = 80;
printf("%d\n", students[0].maths);The dot operator . selects a member of a structure. Compare maths[i] in the old program with students[i].maths in the new program. For a student name, use students[i].name. The array index chooses the student; the dot chooses a field within that student.
4. Modify addStudent() and displayData()
printf("Enter name: ");
scanf("%49s", students[n].name);
printf("Enter Maths mark: ");
scanf("%d", &students[n].maths);
printf("Enter English mark: ");
scanf("%d", &students[n].english);
n++;The program stores all three values in students[n] before increasing n. When displaying records, a for loop prints students[i].name, students[i].maths, and students[i].english. We still use one-word names in this introductory program.
5. Save an entire structure in a binary file
FILE *fp = fopen("students_struct.dat", "wb");
fwrite(&n, sizeof(n), 1, fp);
for (int i = 0; i < n; i++) {
fwrite(&students[i], sizeof(students[i]), 1, fp);
}
fclose(fp);We first save n. Then each call to fwrite() saves the bytes occupied by one struct Student. This replaces the three separate writes per student from the previous tutorial. sizeof(students[i]) gives the complete structure size, which may include extra padding bytes inserted by the compiler.
6. Load the structures in the same order
FILE *fp = fopen("students_struct.dat", "rb");
int count;
fread(&count, sizeof(count), 1, fp);
for (int i = 0; i < count; i++) {
fread(&students[i], sizeof(students[i]), 1, fp);
}
fclose(fp);The saved count comes first, followed by the student structures. The full program below checks the count, file opening, and read results before accepting records. It also ensures that the last character of each name is the string terminator \0.
We use a new file name, students_struct.dat, because this structure-based file layout is different from the previous binary tutorial’s layout. The new program does not automatically convert students.dat. Raw structures are suitable for learning, but their padding, integer sizes, and byte order can vary across systems; they are not a portable file format.
7. Complete C program: array of structures
Copy this program into a new Code::Blocks C project. Compare its struct Student, addStudent(), displayData(), saveData(), and loadData() functions with the previous tutorial.
#include <stdio.h>
#define MAX 100
struct Student {
char name[50];
int maths;
int english;
};
struct Student students[MAX];
int n = 0;
void loadData() {
FILE *fp = fopen("students_struct.dat", "rb");
if (fp == NULL) return;
int count;
if (fread(&count, sizeof(count), 1, fp) != 1 ||
count < 0 || count > MAX) {
printf("Invalid data file.\n");
fclose(fp);
return;
}
for (int i = 0; i < count; i++) {
if (fread(&students[i], sizeof(students[i]), 1, fp) != 1) {
printf("Incomplete record in data file.\n");
n = i;
fclose(fp);
return;
}
students[i].name[49] = '\0';
n++;
}
fclose(fp);
}
void saveData() {
FILE *fp = fopen("students_struct.dat", "wb");
if (fp == NULL) {
printf("Cannot open file for writing.\n");
return;
}
int ok = (fwrite(&n, sizeof(n), 1, fp) == 1);
for (int i = 0; i < n && ok; i++) {
if (fwrite(&students[i], sizeof(students[i]), 1, fp) != 1)
ok = 0;
}
if (fclose(fp) != 0) ok = 0;
if (ok) printf("Records saved.\n");
else printf("Error while saving.\n");
}
void addStudent() {
if (n >= MAX) {
printf("Student array is full.\n");
return;
}
printf("Enter name (one word): ");
if (scanf("%49s", students[n].name) != 1) return;
printf("Enter Maths mark: ");
if (scanf("%d", &students[n].maths) != 1) return;
printf("Enter English mark: ");
if (scanf("%d", &students[n].english) != 1) return;
n++;
}
void displayData() {
printf("\nName\tMaths\tEnglish\n");
for (int i = 0; i < n; i++) {
printf("%s\t%d\t%d\n",
students[i].name,
students[i].maths,
students[i].english);
}
}
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 program. Add John (75, 80), Mary (90, 85), and Peter (65, 70). Display the records.
- Save the records. Locate
students_struct.datin the working directory. - Exit, run the program again, and verify that the same three students load.
- Add Sarah (88, 92), save, restart, and check that four students appear.
- Identify each occurrence of
students[i].name,students[i].maths, andstudents[i].english. Explain what the index and dot operator do.
9. Check your understanding
- What is a structure in C?
- How is an array of structures different from three parallel arrays?
- What does
struct Student students[MAX];declare? - In
students[2].maths, what does[2]select and what does.mathsselect? - Why do we use
&students[i]withfwrite()? - What does
sizeof(students[i])measure? - Why must the loading function read the count before the records?
- Why does this tutorial use
students_struct.datinstead of the previousstudents.dat?
10. Programming challenges
- Add a
computerSciencemark tostruct Student, then update the input and display functions. Use a new file name after changing the structure layout. - Write a function that calculates each student’s average mark.
- Write a function that finds the student with the highest Mathematics mark.
- Modify the menu so Exit automatically calls
saveData(). - Investigate the difference between saving an entire structure and saving each member separately. Which method would be easier to exchange between different computers?
Summary
Parallel arrays store each field in a separate array. An array of structures stores related fields together as student records. The dot operator selects members, and fwrite()/fread() can save and load a complete structure in one operation. The same record-count and menu ideas from earlier lessons still apply.
© 2024 Vedesh Kungebeharry. All rights reserved.
