Use the following structure to implement the functions below: struct Student { c
ID: 3778884 • Letter: U
Question
Use the following structure to implement the functions below:
struct Student { char name[32]; int number; float gpa; }
1. Write a C function that reads from the user (a) the number of student records to read and (2) student records (name, number, and gpa), and returns the list of the student records. You should use dynamic memory allocation. (You do not need to use a linked list.)
2. Write a C function that writes the student records to the file “student.db.”
3. Write a C function that switches the pth record and qth record in the file. The filename, p and q must be passed to this function.
4. Write a main function that tests the above functions. You should print (1) the original student records and (2) the student records after switching some records. All the functions including main() should be included in a file.
Explanation / Answer
Here is the code for you:
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char name[32];
int number;
float gpa;
};
//1. Write a C function that reads from the user (a) the number of student records to read
//and (2) student records (name, number, and gpa), and returns the list of the student records.
//You should use dynamic memory allocation. (You do not need to use a linked list.)
struct Student* readValues()
{
int numOfRecords;
printf("Enter the number of student records to read: ");
scanf("%i", &numOfRecords);
struct Student *student = (struct Student *)malloc(sizeof(struct Student) * numOfRecords);
for(int i = 0; i < numOfRecords; i++)
{
printf("Enter the name of the student #%i: ", i+1);
scanf("%s", student->name);
printf("Enter the number of student #%i: ", i+1);
scanf("%i", &(student->number));
printf("Enter the gpa of student #%i: ", i+1);
scanf("%f", &(student->gpa));
}
return student;
}
//2. Write a C function that writes the student records to the file “student.db.”
void writeToFile(struct Student *student, int n)
{
FILE *fp = fopen("student.db", "w");
for(int i = 0; i < n; i++)
{
fprintf(fp, "%s %d %f ", student->name, student->number, student->gpa);
}
}
//3. Write a C function that switches the pth record and qth record in the file. The filename, p and q must be passed to this function.
void swapRecords(struct Student *student, int n, int p, int q)
{
struct Student students[10];
FILE *fp = fopen("student.db", "r");
for(int i = 0; i < n; i++)
fscanf(fp, "%s%d%f", students[i].name, &students[i].number, &students[i].gpa);
struct Student temp;
temp = students[p+1];
students[p+1] = students[q+1];
students[q+1] = temp;
writeToFile(students, n);
}