C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Store student records in file

C Program: Store and Display Student Records in a File

C

#include <stdio.h>

#include <stdlib.h>

 

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    FILE *file;

    struct Student s;

    int n, i;

 

    // Step 1: Open file in write mode

    file = fopen("students.txt", "w");

 

    if (file == NULL) {

        printf("Error! Cannot open file.\n");

        return 1;

    }

 

    // Step 2: Get number of students

    printf("Enter number of students: ");

    scanf("%d", &n);

 

    // Step 3: Get and write student records

    for (i = 0; i < n; i++) {

        printf("\nEnter details of student %d\n", i + 1);

        printf("Roll Number: ");

        scanf("%d", &s.roll);

        printf("Name: ");

        scanf("%s", s.name);

        printf("Marks: ");

        scanf("%f", &s.marks);

 

        fprintf(file, "%d %s %.2f\n", s.roll, s.name, s.marks);

    }

 

    fclose(file);

    printf("\nStudent records stored successfully in 'students.txt'.\n");

 

    // Step 4: Reopen file to display contents

    file = fopen("students.txt", "r");

 

    if (file == NULL) {

        printf("Error! Cannot open file.\n");

        return 1;

    }

 

    printf("\n--- Student Records ---\n");

    while (fscanf(file, "%d %s %f", &s.roll, s.name, &s.marks) != EOF) {

        printf("Roll: %d\tName: %s\tMarks: %.2f\n", s.roll, s.name, s.marks);

    }

 

    fclose(file);

    return 0;

}

Output

 
OUTPUT :

Enter number of students: 3

Enter details of student 1
Roll Number: 101
Name: Alice
Marks: 85.5

Enter details of student 2
Roll Number: 102
Name: Bob
Marks: 91.0

Enter details of student 3
Roll Number: 103
Name: Carol
Marks: 78.5

Student records stored successfully in 'students.txt'.

--- Student Records ---
Roll: 101   Name: Alice Marks: 85.50
Roll: 102   Name: Bob   Marks: 91.00
Roll: 103   Name: Carol Marks: 78.50

Explanation

Step

Description

1

Defines a structure Student to hold roll, name, and marks.

2

Opens a file (students.txt) in write mode to store data.

3

Accepts input for each student and writes using fprintf().

4

Reopens the file in read mode.

5

Reads back and displays all stored records using fscanf().

6

Closes the file safely.