2013-02-26 5 views
1

HTTP 요청을 받아 소량의 데이터를 추출하는 함수를 작성하려고합니다. 내 기능은 다음과 같습니다 : 분명히 잘못 GET /?f=fibGET /favicon.ico HTTP/1.1strtok(), ftoken 인쇄를 호출 한 후, 현재 GET /?f=fib&n=10 HTTP/1.1strtok()을 사용하여 C로 문자열 토큰 화하기

:

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

은 일반적으로 다음과 같이 보일 것입니다. 이상적으로, 그것은 f=fib이고 atokenn=10 일 것입니다 누군가 제가 이것을 알아내는 데 도움이 될 수 있습니까?

+0

어떻게해야 내가 여기에 대신 롤 strtok''피할 것이다 – fatrock92

+1

같은 출력보기 내 자신의 기능. – dreamlax

+0

'strtok'은 놀랍습니다. 나는 이것을 거의 매일 사용한다. 문자열 파싱을위한 또 다른 좋은 기능은'sscanf'입니다. – fatrock92

답변

1

입력 ->GET /?f=fib&n=10 HTTP/1.1

출력 -> ftoken f=fib 및 atoken 10

코드 ->

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' 
+0

작동하는 것처럼 보입니다. 감사합니다! 마지막 질문 하나. 일단 'atoken'= 'n = 10'이되면 "n ="부분을 제거하기 위해 토큰을 앞당길 수있는 방법이 있습니까? 아니면 그냥 strtok() 호출을 수정해야합니까? 그렇다면 무엇을 바꾸겠습니까? – iaacp

+0

나는 이것을 포함하도록 위의 대답을 편집했다. – fatrock92

+0

다시 한번 감사드립니다. 그냥 호기심,'atoken = strtok (atoken, "=");'허용할까요? 나는이 언어에 익숙하지 않고, 같은 변수를 가진 함수를 호출 할 수 있는지 확신 할 수 없다. – iaacp