1

我正在尝试编写一个接受 HTTP 请求并提取少量数据的函数。我的功能如下所示:

char* handle_request(char * req) {
    char * ftoken; // this will be a token that we pull out of the 'path' variable 
    // for example, in req (below), this will be "f=fib"
    char * atoken; // A token representing the argument to the function, i.e., "n=10"     
        ...

    // Need to set the 'ftoken' variable to the first arg of the path variable.
    // Use the strtok function to do this
    ftoken = strtok(req, "&");
    printf("ftoken = %s", ftoken);

    // TODO: set atoken to the n= argument;
    atoken = strtok(NULL, "");
    printf("atoken = %s", atoken);
   }

req通常看起来像这样:GET /?f=fib&n=10 HTTP/1.1

目前,在调用 之后strtok()ftoken打印出来GET /?f=fibGET /favicon.ico HTTP/1.1显然是错误的。理想情况下,它将是f=fib并且atoken将是n=10任何人都可以帮我解决这个问题吗?

4

1 回答 1

1

输入->GET /?f=fib&n=10 HTTP/1.1

输出 -> ftokenf=fib和 atoken10

代码 ->

ftoken = strtok(req, "?"); // This tokenizes the string till ?
ftoken = strtok(NULL, "&"); // This tokenizes the string till & 
                            // and stores the results in ftoken
printf("ftoken = %s", ftoken); // Result should be -> 'f=fib'

atoken = strtok(NULL, "="); // This tokenizes the string till =.
atoken = strtok(NULL, " "); // This tokenizes the string till next space.
printf("atoken = %s", atoken); // Result should be -> 'n=10'
于 2013-02-26T03:45:46.513 回答