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
#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