Hello,
I am trying to read a file and input it to a structure
So far I have been able to input first three items
but to input the last item (name) i need to use fgets? becasue the name contains whitespaces
how can I go about this?
Thanks
Sean
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int registration_number;
int year;
char degree_scheme[20];
char name[30];
}rec;
int readRec(FILE *fp, rec *record);
int main(void)
{
FILE *f;
int i;
rec recs[10];
f = fopen ("students.txt", "r" );
if ( f == NULL ){
printf("Cannot open record file");
exit(1);
}
for (i = 0; i < 10 && readRec(f, &recs[i]); ++i)
{
printf("%d %d %s %s\n", recs[i].registration_number, recs[i].year, recs[i].degree_scheme, recs[i].name);
}
return 0;
}
int readRec(FILE *fp, rec *record)
{
return fscanf(fp, "%d %d %s", &record->registration_number, &record->year, record->degree_scheme) == 3;
}
sample data
Code:
32553 1 PCS dsgasd sdagasd
32153 2 JHM asdgag sgsd
34662 3 PCS asdg sdgas
36446 1 JHM sgdsga gasdg
23325 3 JHM gdsagasd gasdg
23532 2 JHM asdgsa gsdgsa