C - strtok 和 strcmp

标签 c strtok strcmp

我在使用带有 strcmp 的 strtok 时遇到了一些麻烦。

//Handles the header sent by the browser
char* handleHeader(char *header){
        //Method given by browser (will only take GET, POST, and HEAD)
        char *method,*path, *httpVer;

        method = (char*)malloc(strlen(header)+1);
        strcpy(method,header);
        method = strtok(method," ");


        path = strtok(NULL," ");
        httpVer = strtok(NULL, " ");
        printf("\nMethod: %s\nPath: %s\nHTTP: %s\n",method,path,httpVer);


        printf("\nc1: %d\nc2: %d\n",strcmp(httpVer,"HTTP/1.0"),strcmp(httpVer,"HTTP/1.1"));

        if(!(!strcmp(httpVer,"HTTP/1.0") || (!strcmp(httpVer,"HTTP/1.1")))){
                printf("\ngive a 400 error\n");
                return "400 foo";
        }


        if(!strcmp(method,"GET")){
                //char *path = strtok(NULL," ");

                //If they request the root file, change the path to index.html
                if(!strcmp(path,"/")){
                        path = (char*)malloc(strlen(BASE_DIR) + strlen("/index.html")+1);
                        strcpy(path,"/index.html");
                }
                 return readPage(path,2);
        }
}

如果我给它下面的标题

GET / HTTP/1.0

我得到这个输出:

Method: GET
Path: /
HTTP: HTTP/1.0


c1: 1
c2: -1

give a 400 error

如您所见,strtok() 可以正确解析字符串,但 c1 和 c2 的值似乎没有意义(c1 应该返回 0,但它返回 1)。

这是怎么回事?

最佳答案

我猜你不会给它这个:

GET / HTTP/1.0

而是这样:

GET / HTTP/1.0\n

或者可能是这样的:

GET / HTTP/1.0\r\n

查看您的代码,“HTTP”输出行和“c1”行之间应该有一个空白行,但您有两个,这意味着“HTTP”值本身包含换行符。

在值周围输出一些引号 - 我敢打赌你会看到:

HTTP: "HTTP/1.0
"

关于C - strtok 和 strcmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1449401/

相关文章:

c - ANSI C : How to split a string by newline and get a random line

c - 将文件中的字符串拆分为c中的数组

c++ - strtok 使用了错误的分隔符(空格以及 ",")

c++ - 当我调用 strcmp 从 'int' 到 'const char*' 的无效转换时出错

c - 硬编码指针值

c - fgets 不移动文件指针

c - 对指向指针 "array"的指针的单个 malloc 调用导致无效写入

c - 尝试运行自定义 shell 时出现段错误

C++比较字节数组和结构的最佳方法

c - 错误: too few arguments to function 'strcmp'