0

我有以下 C 字符串:

char teste[] = "POST /index.html HTTP/1.1\nHost: localhost:8000\nConnection: keep-alive\nContent-Length: 23\nCache-Control: max-age=0\nAccept: text/html,application/xhtml+x
ml,application/xml;q=0.9,*/*;q=0.8\n Origin: http://localhost:8000\nUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/
537.36\nContent-Type: application/x-www-form-urlencoded\nReferer: http://localhost:8000/index.html\nAccept-Encoding: gzip,deflate,sdch\nAccept-Language: pt-BR,pt;q=0.8,en-US;q=
0.6,en;q=0.4\n\nnome=thiago&idade=12313";

我需要提取 POST 参数,这发生在 '\n\n' 之后:

\n\nnome=thiago&idade=12313";

strtok似乎卡在第一个'\ n'上,所以我认为有更好的方法来做到这一点。到目前为止我的代码:

char *token = malloc(100);
char **value  = malloc(100 * sizeof(char *));
char **key  = malloc(100 * sizeof(char *));
int i;

for(i = 0; i < 100; i++)
{
   value[i] = malloc(100);
   key[i] = malloc(100);
}

/* This doesn't work */ 
token = strtok(teste, "\n\n");

关于如何解决这个问题的任何想法?谢谢!

4

1 回答 1

1

您可以使用strstr()来定位参数的开始:

char *params = strstr(teste, "\n\n");
if (params != NULL) {
    params += 2; // now points to first key
    // ...
}

然后用于strtok()分隔 中的键值对params

备注: strtok_r()是 的可重入版本strtok(),并且(至少在 OS X 上) strtok()已被strsep().

于 2013-09-04T20:44:18.653 回答