strtok 及其用法

strtok and it's usage

我正在做一项需要字符串和文件操作的作业。我目前正在研究字符串操作部分,我正在尝试使用 strtok 来分隔文件中的行,用逗号分隔。但是,我不确定 strtok 是如何工作的。我正在查看下面的代码,但不太明白为什么在第二个 strtok 调用中有一个 NULL,而 NULL 甚至不是一个字符串。

我的代码是运行:

/******************************************** ************************ * * 目的:演示'strtok'函数的程序。 * 作者:M J Leslie * 日期:23-Apr-94 * ****************************************************** **************/

#include <stdio.h>
#include <string.h>

main()
{
            /* Copy the constant into the memory
             * pinted to by 'test_string'       */
    char test_string[50]="string to split up";

    /* if 'test_string' is declared as below and the program will give a 
    * 'Segmentation fault' This is because test_string' is pointing
    * to a constant i.e. somethin that cant be changed.     

    char *test_string="string to split up";         */

    char *sub_string;

                /* Extract first string */
    printf("%s\n", strtok(test_string, " "));

                /* Extract remaining 
                 * strings      */
    while ( (sub_string=strtok(NULL, " ")) != NULL)
    {
         printf("%s\n", sub_string);
    }
 }
 /*****************************************************************
 *
 * Program O/P will look like this...
 *
 *   string
 *   to
 *   split
 *   up
 *
 *****************************************************************/

来自documentation

Each subsequent call, with a null pointer as the value of the first argument, starts searching from the saved pointer and behaves as described above.