This blog is under construction

Saturday 29 June 2013

C program to store students records in a file

Write a C program to store student records in a file.


  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  struct studentdb {
        char name[100];
        int s1, s2, s3;
        float avg;
        int rollno;
        char grade;
  };

  int main() {
        struct studentdb *s;
        int i, n;
        FILE *fp;

        /* open file in write mode to store student details */
        fp = fopen("studentDB.txt", "w");

        /* enter the no of students */
        printf("Enter the number of students:");
        scanf("%d", &n);

        /* dynamically allocate memory to store student details */
        s = (struct studentdb *)malloc(sizeof (struct studentdb) * n);

        /* get the student details from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++) {
                printf("Input for student %d:\n", i + 1);
                getchar();
                printf("Name:");
                fgets(s[i].name, 100, stdin);
                s[i].name[strlen(s[i].name) - 1] = '\0';
                printf("Marks in Eng, science and Maths:");
                scanf("%d%d%d", &s[i].s1, &s[i].s2, &s[i].s3);
                printf("Rollno:");
                scanf("%d", &s[i].rollno);
        }

        /* store the student details in studentDB.txt */
        fprintf(fp, "RollNo    Name           s1   s2   s3   Grade  avg\n");
        fprintf(fp, "---------------------------------------------------\n");
        for (i = 0; i < n; i++) {
                fprintf(fp, "%-10d%-15s", s[i].rollno, s[i].name);
                fprintf(fp, "%5d%5d%5d", s[i].s1, s[i].s2, s[i].s3);
                s[i].avg = (s[i].s1 + s[i].s2 + s[i].s3) / 3;
                if (s[i].avg > 80)
                        s[i].grade = 'A';
                else if(s[i].avg > 60)
                        s[i].grade = 'B';
                else
                        s[i].grade = 'C';
                fprintf(fp, "%4c %4.2f\n", s[i].grade, s[i].avg);
        }

        /* close the file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of students:3

  Enter your inputs:
  Input for student 1:
  Name:Anand 
  Marks in Eng, science and Maths:98  97  95
  Rollno:1

  Input for student 2:
  Name:Bala
  Marks in Eng, science and Maths:95  93  94
  Rollno:2

  Input for student 3:
  Name:Sam
  Marks in Eng, science and Maths:99  97  100
  Rollno:3

  jp@jp-VirtualBox:~/$ cat studentDB.txt 
  RollNo    Name           s1   s2   s3   Grade  avg
  ---------------------------------------------------
  1         Anand             98   97   95   A 96.00
  2         Bala                95   93   94   A 94.00
  3         Sam                99   97  100   A 98.00



No comments:

Post a Comment