Sunday, January 12, 2020

Write a student data into a file using the C Structure

File Management using C Structure

This C Program will write a student data into a file using the Structure and File Management concept of C programming.

Source Code

#include <stdio.h>
//Structure to store student data.
struct student
{
   char fname[30];
   char lname[30];
   int  rollno;
   float percentage;
};

void main ()
{
   FILE *fp;
   //declare structure(student) variable
   struct student input;
   // open student file for writing
   fp = fopen ("student.dat","w");
   if (fp == NULL){
      printf("\nFile opening error..\n\n");
      exit (1);
     }

   printf("Enter \"exit\" as First Name to stop reading user input.");

   while (1)
     {
      printf("\nFirst Name: ");
      scanf ("%s", input.fname);
     
      if (strcmp(input.fname, "exit") == 0)
         exit(1);
     
      printf("Last Name : ");
      scanf ("%s", input.lname);
      printf("Roll Number  : ");
      scanf ("%d", &input.rollno);
      printf("Percentage : ");
      scanf ("%f", &input.percentage);

      // write student data to student.dat  file
      fwrite (&input, sizeof(struct student), 1, fp);
     }
}

Output of program 

Enter "exit" as First Name to stop reading user input.
First Name: K
Last Name : Patel
Roll Number  : 101
Percentage : 90.50

First Name: ABC
Last Name : Shah
Roll Number  : 102
Percentage : 95.50

First Name: exit

* * * * *


< Read more about C File Management >

< Read more about C Structure >

< Back to Home Page>



No comments:

Post a Comment