Using fgets() and strtok() to read in a file line-by-line in C?

后端 未结 4 1789
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 07:03

I\'m trying to use fgets and strtok() to read in a file line by line, and create a linked list of each different line of information.

Right now, I\'m only just putt

4条回答
  •  囚心锁ツ
    2020-12-09 07:47

    strtok() returns pointers inside line[] so when you read the next line all the pointers you saved are now pointing to places where the last line of the file is stored.

    You could allocate memory for each bit of string like so:

    //load last name
    value = strtok(line, ",");
    result[i][0] = malloc(strlen(value) + 1);
    strcpy(result[i][0], value);
    

    As an aside, you don't need the loops at the start to set everything to NULL, you could do this instead:

    char *result[10][4] = {0};
    

提交回复
热议问题