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

后端 未结 4 1796
被撕碎了的回忆
被撕碎了的回忆 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:40

    You need to copy the tokens into a separate storage if you need them.

    strtok() will modify the buffer that you reads the line in, and replace the delimiters with NUL character, and return a pointer to certain position in the buffer (that is the start of the current token).

    When you read in the next line, the buffer will be filled with new data, hence, all the pointers that you have saved are useless, since the previous data is now gone.

    Quote from documentation:

    To determine the beginning and the end of a token, the function first scans from the starting location for the first character not contained in delimiters (which becomes the beginning of the token). And then scans starting from this beginning of the token for the first character contained in delimiters, which becomes the end of the token.

    This end of the token is automatically replaced by a null-character by the function, and the beginning of the token is returned by the function.

    And (emphasis mine):

    str
    C string to truncate. The contents of this string are modified and broken into smaller strings (tokens).
    Alternatively, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

    delimiters:
    C string containing the delimiters.
    These may vary from one call to another.

提交回复
热议问题