开发者

Passing fscanf to struct

I'm trying to open a file and pass to struct, I'm using fscanf() with a loop, but it only saves one the struct the last read:

Imagine a file:

JR John Rambo 24353432 
JL John Lennon 6435463

I'm using this 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 is that he only sa开发者_如何学Cves the last line of the file...Should I do a if cicle??

Another question is how can I separate a similar file but with ";"


First of all, you are scanning for 3 strings (%s) and one int (%d) when you pass only 3 parameters in your fscanf(). You could add a char first_name[50]; in your struct and then 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 always fscanf() the file until you have nothing more to read (due to the !feof(fp) because of the while. So in the last people[n_p] variable the last line of the file will be saved.

You could remove the while from read() and also add the FILE * as a parameter to the function so that you don't open the file each time you call read().

Something like this maybe:

main()
{
   FILE* fp = fopen("example.txt", "r");
   int i = 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 the ; as a separator you can change fscanf() to this:

 fscanf(fp, "%[^;]; %[^;]; %d\n", people[n_p].code,people[n_p].name,
             &people[n_p].telephone);

EDIT I wrote the above code which can be found here and it works fine with this example.txt file as input.


It looks like you're not changing the n_p variable. You need some sort of variable to keep track of which index of the people[] array you're updating.

Additionally, hopefully you've got a large enough people array to hold all the entries in the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜