我在使用strcmp和strtok時遇到了一些麻煩。C - strtok和strcmp
//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)。
這是怎麼回事?
就想到這個問題。 @ Steven1350,請嘗試使用strstr而不是strcmp來查看是否發生這種情況。 – Zed 2009-09-19 20:11:00
用strstr替換strcmp,我得到以下內容: c1:163160734 c2:0 – 2009-09-19 20:14:52
c1不爲零意味着字符串'HTTP/1.0'出現在'httpVer'中。 – RichieHindle 2009-09-19 20:17:17