Write a program to take input for students (id, name, cgpa) until id is given zero, put those student info into a linked list or add those student info at the tail of linked list. After adding all those students, print all student info into a binary file. Create another program to read the entries again.
The first program for write
#include <stdio.h>
#include <stdlib.h>
struct student {
char id[8];
char name[20];
float cgpa;
} s[1000];
int main() {
int n;
FILE *fptr; // declaring a variable for binary file
if ((fptr = fopen("program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
int i = 0;
printf("Enter information of students:\n");
//storing information
while (1) {
printf("For the %d - student: \n", i + 1);
printf("Enter student id: ");
scanf("%s", s[i].id);
printf("Enter student name: ");
scanf("%s", s[i].name);
printf("Enter student cpga: ");
scanf("%f", &s[i].cgpa);
if (s[i].cgpa == 0) {
break;
}
i++;
printf("\n");
fwrite(&s[i], sizeof(struct student), 1, fptr);
}
fclose(fptr);
}
A second program for reading a binary file
#include <stdio.h>
#include <stdlib.h>
struct student {
char id[8];
char name[20];
float cgpa;
} s[1000];
int main() {
int i = 0;
int n;
FILE *fptr; // declaring a variable for binary file
if ((fptr = fopen("program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for (n = 0; n < 5; n++) {
fread(&s[i], sizeof(struct student), 1, fptr);
printf("For the %d - student: \n", i + 1);
printf("Student id: %s\nStudent name: %ds\nStudent cgpa: %f", s[i].id, s[i].name, s[i].cgpa);
i++;
}
fclose(fptr);
}
Comments
Leave a comment