简体   繁体   中英

Reading from file and storing into an array of structs

I have a simple file formatted as such

NAME|VALUE
NAME|VALUE
NAME|VALUE

I am trying to read these in, and store them in an array of structs, the struct is this

struct data
{
    char* name;
    char* value;
};

For now, I know the size of the array will be 3, so I did this:

struct data pairs[3];

Here is my code as I am trying to read it in from the file:

char *tempVal;
int i =0;
    if(file != NULL)
        {
            char curLine [128];
            while(fgets(curLine, sizeof curLine, stockFile) != NULL)
            {   

                tempVal = strtok(curLine,"|");
                printf("i:%i\n",i);
                pairs[i].name= tempVal;
                printf("name at pos %i is %s\n",i, pairs[i].name);
                tempVal = strtok(NULL,"|");
                pairs[i].value= tempVal;
                printf("value at pos %i is %s\n",i, pairs[i].value);
                ++i;
            }
            fclose(file);
        }

and each of those printf statments prints the correct thing along the way, then I try to print the array with this

int j
for(j = 0; j < 3; j++)
    {   

        printf("ENTRY# %i\NAME:%s\VALUE:%s\n\n",j,pairs[j].name, pairs[j].value);
    }

Sorry the indentation is a little weird, tried messing with the code blocks but couldn't get it quite perfect. However, I am wondering why it shows the correct thing during the while loop as it goes along, but then after it is complete the for loop shows all three of the array entries having the same name(the value is correct for the third entry but for the first and second entries the value field contains half of the correct value for the third entry)

Thanks!

The value returned from strtok() will be pointing to an element in curLine , so all entries in the array of struct s will be pointing to an element in curLine which is overwritten with each call to fgets() (and will only be valid for the current iteration).

You should make a copy of the value returned from strtok() during the while , possibly using strdup() :

while(fgets(curLine, sizeof curLine, stockFile) != NULL)
{   
    tempVal = strtok(curLine,"|");
    printf("i:%i\n",i);
    pairs[i].name = strdup(tempVal);
    printf("name at pos %i is %s\n",i, pairs[i].name);
    tempVal = strtok(NULL,"|");
    pairs[i].value = strdup(tempVal);
    printf("value at pos %i is %s\n",i, pairs[i].value);
    ++i;
}

free() them later when no longer required:

for (j = 0; j < 3; j++)
{
    free(pairs[j].name);
    free(pairs[j].value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM