Home »
Code Snippets »
C/C++ Code Snippets
C program to input student details in a file, save and extract them as records
This program is asked by Sam Atkinson Amerity through comment on 14/12/2016.
Question
HI I have got assignment to write a program in c , it is like a grade convener to alphabet the input must be name subject score and grade until the end of input,1. with E0F / ctrl z. the output must be number name subject score grade . print the position who gets A . and 2. from table number 1 short it from the lowest score and then print the position of a . 3 short from the name of student and print the position who got A.
Answer
Here, we are reading records just like file input and saving them into a file, file is terminating by pressing ‘#’ character.
To extract records, we are reading character by character and putting them into a string as we found new line character value (0xA) – that will be the complete one record and so on...
#include <stdio.h>
#define SIZE 1024
int main()
{
char text[SIZE]={0},record[100];
char ch;
int cnt=0,len;
FILE *fp; /*file pointer*/
/*create file*/
fp=fopen("file1.txt","w");
if(fp==NULL)
{
printf("Error in creating file");
return -1;
}
printf("Enter student details line wise (press # to save and close):\n");
while(1)
{
ch=getchar();
if(ch=='#')
{
break;
}
fputc(ch,fp);
}
fclose(fp); //close the file
printf("File saved successfully\n");
/*open file*/
fp=fopen("file1.txt","r");
if(fp==NULL)
{
printf("Error in opening file.\n");
return -1;
}
printf("Entered records are:\n");
//read content from file
cnt=0;
while((ch=fgetc(fp))!=EOF)
{
if(ch==0x0A)//check new line
{
record[cnt++]='\0';
cnt=0;
printf("%s\n", record);
continue;
}
record[cnt++]=ch;
}
fclose(fp);
return 0;
}
Output
Enter student details line wise (press # to save and close):
ABC 80 A
PQR 90 A
XYZ 70 B
#
File saved successfully
Entered records are:
ABC 80 A
PQR 90 A
XYZ 70 B
How to extract values from this record
Since file is not written through a structure (file contains characters), that’s why we separated each value through space
Let suppose one record (with name, subject score and grade) is:
ABC 80 A
Consider the following code to extract values from this string
#include <stdio.h>
int main()
{
char record[]="ABC 80 A";
char name[30];
int score;
char grade;
sscanf(record,"%s %d %c",name,&score,&grade);
printf("Name: %s\n",name);
printf("Subject score: %d\n",score);
printf("Grade: %c\n",grade);
return 0;
}
Output
Name: ABC
Subject score: 80
Grade: A