c - Passing fscanf to struct -
i'm trying open file , pass struct, i'm using fscanf() loop, saves 1 struct last read:
imagine file:
jr john rambo 24353432 jl john lennon 6435463 i'm using code:
typedef struct people{ char code[10]; char name[100]; long telephone; }people; int read(people people[], int n_p){ char temp; file *fp; fp=fopen("example.txt","r"); if(fp==null){ printf("error\n"); return -1; } while(!feof(fp)){ fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].name, &people[n_p].telephone); } } the problem saves last line of file...should if cicle??
another question how can separate similar file ";"
first of all, scanning 3 strings (%s) , 1 int (%d) when pass 3 parameters in fscanf(). add char first_name[50]; in struct , do:
fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].first_name, people[n_p].name, &people[n_p].telephone); you fscanf() file until have nothing more read (due !feof(fp) because of while. in last people[n_p] variable last line of file saved.
you remove while read() , add file * parameter function don't open file each time call read().
something maybe:
main() { file* fp = fopen("example.txt", "r"); int = 0; while (!feof(fp)) { read(people, i, fp); i++; } } int read(people people[], int n_p, file* fp){ char temp; if(fp==null){ printf("error\n"); return -1; } fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].first_name, people[n_p].name, &people[n_p].telephone); } for using ; separator can change fscanf() this:
fscanf(fp, "%[^;]; %[^;]; %d\n", people[n_p].code,people[n_p].name, &people[n_p].telephone); edit wrote above code can found here , works fine example.txt file input.
Comments
Post a Comment