C Student Records Program Using Structure and File

This program saves the records of students in a file with fwrite(), and then reads them back with fread(). A structure keeps the data of one student. A binary file stores the structure as it is in memory.

#include <stdio.h>

struct Student {
    int roll;
    char name[20];
    float marks;
};

int main(void) {
    struct Student list[3] = {
        {1, "Robin", 85.5f},
        {2, "Maria", 92.0f},
        {3, "John", 78.5f}
    };
    struct Student s;

    // write the records
    FILE *fp = fopen("records.dat", "wb");
    if (fp == NULL) {
        printf("Cannot open the file\n");
        return 1;
    }
    fwrite(list, sizeof(struct Student), 3, fp);
    fclose(fp);

    // read the records back
    fp = fopen("records.dat", "rb");
    if (fp == NULL) return 1;

    printf("Roll  Name    Marks\n");
    while (fread(&s, sizeof(struct Student), 1, fp) == 1) {
        printf("%-5d %-7s %.1f\n", s.roll, s.name, s.marks);
    }
    fclose(fp);
    return 0;
}

Output:

Output of the above program is

Roll Name Marks
1 Robin 85.5
2 Maria 92.0
3 John 78.5

How it works

  • fwrite(ptr, size, count, file) writes count items of size bytes each.
  • fread() returns the number of items read, so the loop stops at the end of the file.
  • The mode "wb" and "rb" means binary write and read.
Note: The binary file is not readable in a text editor, and it can differ on another computer (because of padding and byte order). For files to share, use text files. Related: File Handling and Structures.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.