In: Computer Science
Write down a C program which will create a list (simple linear linked list) of nodes. Each node consists of two fields. The first field is a pointer to a structure that contains a student id (integer) and a grade-point average (float). The second field is a link. The data are to be read from a text file. Your program should read a file of 10 students (with student id and grade point average) and test the function you wrote (by printing student’s information on screen). (Please comment the codes)
//C program
#include<stdio.h>
#include<stdlib.h>
//structure student
struct student{
int id;
float grade;
};
//Node structure
struct Node{
struct student* st;
struct Node*next;
};
//adding new node to link list
struct Node* addNode(struct Node * head , int id , float
grade){
//declaring and memory allocation to struct student
pointer
struct student * newSt = (struct student*)
malloc(sizeof(struct student));
newSt->id = id;
newSt->grade = grade;
//declaring and memory allocation to struct Node
pointer
struct Node* newNode = (struct Node*)
malloc(sizeof(struct Node));
newNode->st = newSt;
newNode->next = NULL;
//if list is empty
if(head==NULL)return newNode;
struct Node*current = head;
while(current->next)current =
current->next;
current->next = newNode;
return head;
}
//funcion to display linkedlist
void display(struct Node*head){
while(head){
printf("ID :
%d\n",head->st->id);
printf("Grade :
%.2f\n\n",head->st->grade);
head = head->next;
}
}
//main driver function
int main(){
//variable declaration
int id;
float grade;
struct Node* head = NULL;
//opening file
FILE* fp = fopen("input.txt", "r"); // read mode
//if file does not opened
if (fp == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
//reading data from file
while (!feof (fp))
{
fscanf (fp, "%d", &id);
fscanf (fp, "%f", &grade);
//adding new data to existing linkedlist as a ne
node
head = addNode(head,id,grade);
}
//displaying linkedlist
display(head);
//closing file
fclose (fp);
return 0;
}