代码之家  ›  专栏  ›  技术社区  ›  chuckfinley

C: strtok值返回null

  •  1
  • chuckfinley  · 技术社区  · 12 年前

    我正在尝试解析HTTP请求标头。我需要选择第一行:

    获取HTTP://1.1

    但是,以下代码的输出是:

    Method: (null)
    Filename: (null)
    Version: (null)
    Client hostname: (null)
    

    为什么?

    代码:

        char *token;
        const char delimiter[2] = " ";
        token = strtok(NULL, delimiter);
    
    2 回复  |  直到 12 年前
        1
  •  4
  •   John Yost    12 年前

    第一次调用strtok时,需要提供要拆分的字符串作为第一个参数。后续对strtok的调用需要使用NULL作为第一个参数,以获得后续的分隔字符串。

    祝你好运

        2
  •  2
  •   martynas    12 年前

    分隔符必须为“\r\n”,否则将连接某些部分

        // Parse the request                                                                                  
        char *token;
        const char delimiter[6] = " \r\n";
    
        token = strtok(buffer, delimiter);
        method = token;
        printf("Method: %s\n", method);
    
        token = strtok(NULL, delimiter);
        filename = token;
        printf("Filename: %s\n", filename);
    
        token = strtok(NULL, delimiter);
        version = token;
        printf("Version: %s\n", version);
    
        while (token != NULL) {
          if (strstr(token, "Host:") != NULL) {
            token = strtok(NULL, delimiter);
            client_hostname = token;
            break;
          }
          token = strtok(NULL, delimiter);
        }
    
        printf("Client hostname: %s\n", client_hostname);