What is wrong in this program ?

P

pereges

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

int main(void)
{
FILE *fp;
int i, n;
typedef struct student_record
{
char name[40];
int sid;
}student;

student s;
/* I presume this creates a new file if one already doesn't exist */
fp = fopen("student.dat", "ab+");
if(fp == NULL)
{
perror("file can't be opened\n!");
exit(EXIT_FAILURE);
}
else
{

printf("How many records you want to write ?\n");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Enter record %d: student name student
id\n", i);

/* There seems to be some problem here and
its obvious during run time */
scanf("%s %d", s.name, &s.sid);
fwrite(&s, sizeof(s),1, fp);
}

}

/* doesn't print at all ? */
while(fread(&s, sizeof(s), 1, fp) == 1)
printf(" %s %d \n", s.name, &s.sid);

return 0;

}

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

The o/p I get :

How many records you want to write ?
3
Enter record 0: student name student id
Nathan Reed 5
Enter record 1: student name student id
Enter record 2: student name student id
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top