C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Retrieve student records from file

C Program: Retrieve student records from file

C

#include <stdio.h>

#include <stdlib.h>

 

struct Student {

    int roll;

    char name[50];

    float marks;

};

 

int main() {

    FILE *file;

    struct Student s;

 

    // Step 1: Open file in read mode

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

 

    if (file == NULL) {

        printf("Error! Cannot open file or file does not exist.\n");

        return 1;

    }

 

    // Step 2: Read and display student records

    printf("\n--- Student Records Retrieved from File ---\n");

    printf("Roll\tName\t\tMarks\n");

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

 

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

        printf("%d\t%-10s\t%.2f\n", s.roll, s.name, s.marks);

    }

 

    fclose(file);

    return 0;

}

Output

 
INPUT :
Assume the file students.txt contains:

101 Alice 85.5
102 Bob 91.0
103 Carol 78.5


OUTPUT :

--- Student Records Retrieved from File ---
Roll    Name            Marks
----------------------------------
101     Alice           85.50
102     Bob             91.00
103     Carol           78.50

Explanation

Step

Description

1

Opens students.txt in read mode using fopen("r").

2

Checks if the file exists — if not, prints an error.

3

Reads data from file using fscanf() and stores it in a Student structure.

4

Displays each student’s record in a tabular format.

5

Closes the file safely using fclose().