我在使用带有 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/