Friday 7 September 2012

Reading a file of students in c

#include <stdio.h>
#include <conio.h>

void main(void)
{
    FILE *stf;
    typedef struct st
        {
            int rno;
            char name[15];
            int subj[3];
        } stud;
    int i,j,n,s;
    char fname[12];
    stud student;

    clrscr();
    printf("Program for Reading the File of Students\n");
    printf("Enter the file name to open : ");
    scanf("%s",fname);
    stf = fopen(fname,"rb");
    if (stf == NULL)
      {
        printf("File Opening Error\n");
        exit(0);
      }
    i = 1;
    fseek(stf,0,SEEK_END);
    s = ftell(stf);
    n = s/sizeof(stud);
    fseek(stf,0,SEEK_SET);
    while (i<=n)
       {
        fread(&student,sizeof(student),1,stf);
        printf("Student %d details\n",i);
        printf("Student %d Roll No. : %d\n",i,student.rno);
        printf("Student %d Name : %s\n",i,student.name);
        printf("Student %d Marks\n",i);
        for (j=1;j<=3;j++)
            printf("\tSubject %d marks : %d\n",j,student.subj[j-1]);
        i++;
       }
    fclose(stf);
    printf("\nPress any key to end...");
    getch();
}

No comments:

Post a Comment