Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Thursday, January 19, 2017

C Program to Store Record In A File

C program to store students records in a file

The main purpose of this program is that to store some information in a file from console.

Code

/*Write a program that will read roll, name and marks of several student from the user and store them in a file*/
#include <stdio.h>
#include <stdlib.h>
//Create a structure for store the records for all students
struct student
{
 int roll;
 char name[30];
 int marks;
} s;
int main( ){
 FILE *fp; //Create a file pointer variable
 char fname[20],s2[20];
 int n,i,s1,s3;
 printf("\nEnter a file name to store student record: ");
 gets(fname);
 //Open the file in write mode
 fp=fopen(fname,"w");
 if(fp==NULL){
  printf("\nError:FIle cannot be created. \a");
  exit(0);
 }
 printf("\nEnter the number of student: ");
 scanf("%d",&n);
 //Taking the records of students and store them in the file
 for(i=0;i<n;i++){
  printf("\nFor student no. %d", i+1);
  printf("\nEnter roll: ");
  scanf("%d",&s.roll);
  printf("\nEnter name: ");
  scanf("%s",&s.name);
  printf("\nEnter marks: ");
  scanf("%d",&s.marks);
  fprintf(fp,"%d\t%s\t%d\n",s.roll,s.name,s.marks);
 }
 //Close the file
 fclose(fp);
 //Open the file in read mode
 fp=fopen(fname,"r");
 if(fp==NULL){
  printf("\nError:FIle does not exist. \a");
  exit(0);
 }
 if(ferror(fp)!=0){
  printf("\nError: File is either corrupted or damaged. \a");
  exit(0);
 }

 //Print the content of the file
 for(i=1;i<=n;i++){
  fscanf(fp,"%d\t%s\t%d\n",&s1,&s2,&s3);
  printf("\n%d\t%s\t%d",s1,s2,s3);
 }
 //Close the file
 fclose(fp);
 return(0);
}

Output

Enter a file name to store student record: student.txt
Enter the number of student: 3
For student no. 1
Enter roll: 101
Enter name: Alex
Enter marks: 85
For student no. 2
Enter roll: 102
Enter name: Rose
Enter marks: 96
For student no. 3
Enter roll: 103
Enter name: Charls
Enter marks: 93
The content of the file is:
101     Alex    85
102     Rose    96
103     Charls  93