0% found this document useful (0 votes)
2 views3 pages

Structure File Record

The document describes a C program that defines a struct for student records and implements file I/O to write and read these records. It prompts the user for multiple student details, writes them to a binary file, and then reads from that file to display the records. Sample input and output are provided to illustrate the program's functionality.

Uploaded by

lionkingsme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Structure File Record

The document describes a C program that defines a struct for student records and implements file I/O to write and read these records. It prompts the user for multiple student details, writes them to a binary file, and then reads from that file to display the records. Sample input and output are provided to illustrate the program's functionality.

Uploaded by

lionkingsme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Program: Write and Read Records Using struct and File I/O

Defines a struct for a student record.

Takes multiple records from the user and writes them to a file.

Reads those records back from the file and displays them.

#include <stdio.h>
#include <stdlib.h>

struct Student {
int id;
char name[50];
float marks;
};

int main() {
FILE *fp;
struct Student s;
int n, i;

// Writing records
fp = fopen("students.dat", "wb"); // open in binary write
mode
if (fp == NULL) {
perror("Error opening file");
return 1;
}

printf("Enter number of students: ");


scanf("%d", &n);

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


printf("\nEnter details for student %d\n", i + 1);
printf("ID: ");
scanf("%d", &s.id);
printf("Name: ");
scanf(" %[^\n]", s.name); // read string with spaces
printf("Marks: ");
scanf("%f", &s.marks);

fwrite(&s, sizeof(s), 1, fp); // write record to file


}

fclose(fp);
printf("\nRecords written successfully.\n");

// Reading records
fp = fopen("students.dat", "rb"); // open in binary read
mode
if (fp == NULL) {
perror("Error opening file");
return 1;
}

printf("\nReading records from file:\n");

while (fread(&s, sizeof(s), 1, fp)) {


printf("\nID: %d\nName: %s\nMarks: %.2f\n", s.id,
s.name, s.marks);
}

fclose(fp);
return 0;
}
Sample input/output

Enter number of students: 2

Enter details for student 1


ID: 101
Name: Alice Johnson
Marks: 88.5

Enter details for student 2


ID: 102
Name: Bob Smith
Marks: 92.0

Records written successfully.

Reading records from file:

ID: 101
Name: Alice Johnson
Marks: 88.50

ID: 102
Name: Bob Smith
Marks: 92.00

You might also like