Reading and parsing lines from a file with fgets and strtok

后端 未结 2 1252
青春惊慌失措
青春惊慌失措 2021-01-13 23:57

I\'m having trouble with a fairly basic bit of code. I need to read each line from the file shown below, split it up into the 3 parts with strtok, and store each part into a

2条回答
  •  囚心锁ツ
    2021-01-14 00:40

    strtok returns a pointer to a null-terminated string containing the next token. To actually copy this token, you should use strcpy:

    strcpy(names[i],    strtok(buffer,      " \n"));
    strcpy(goals[i],    atoi(strtok(NULL,   " \n")));
    strcpy(assists[i],  atoi(strtok(NULL,   " \n")));
    

    Also note that there is a memory leak in your code:

    void readLinesFromFile(/*...*/)
    {
        char * buffer = malloc(MAX_LINE*sizeof(char));
        // ...
        fgets(buffer, MAX_LINE, fPtr);
        // ...
    }
    

    You dynamically allocate the buffer by calling malloc, but you don't free this memory. Don't forget to call free() on a pointer pointing to the memory that has been allocated by malloc. But in this case, the array with automatic storage duration would be a better choice:

    void readLinesFromFile(/*...*/)
    {
        char buffer[MAX_LINE];
        // ...
        fgets(&buffer, MAX_LINE, fPtr);
        // ...
    }
    

提交回复
热议问题