C:从u_char中解析子字符串*

时间:2013-11-14 22:35:15

标签: c parsing substring strstr

我很难找到u_char *中子字符串的开头, 我试图获得“q =”的位置来解析URL中的谷歌搜索 这让我疯了,我真的很感激,如果有人能帮助我的话。 我的C知识有限。

这是我坚持的行:if(g_start = strstr(final_url, "q=") != NULL){

以下是我的部分代码:

int  url_length,host_length, search_length;
u_char *url, *end_url, *final_url, *host, *end_host, *final_host, *ghostUrl, *google, *g_end, *g_start;


/* copy  host + url to a null terminated c string */
final_url = (u_char*)malloc(url_length + 1); //malloc ( length )  +1 for \0
final_host = (u_char*)malloc(host_length +1);
strncpy((char*)final_host,(char*)host, host_length);
strncpy((char*)final_url, (char*)url, url_length);
final_url[url_length] = '\0'; //null terminerer
final_host[host_length] = '\0';

    /* Everything above works fine.. */
   /* final_url looks like this: /search?biw=320&bih=570&tbm=isch&sa=1&ei=M0eFUsXvHOO54AS644GYCQ&q=dogs&oq=dogs&gs_l=mobile-gws-serp.12...0.0.0.1991659.0.0.0.0.0.0.0.0 */

if(strcmp("www.google.no", final_host) == 0){ /* host: www.google.no */
    if(g_start = strstr(final_url, "q=") != NULL){ /* This fails.. */       
printf("debug: search starts at %s\n", g_start); /* I have no idea.. how to get integer position from strstr()  */
    g_end = strchr((char*)g_start,'&'); // ?q=dogs[&]
    search_length = g_end - g_start;

    printf("DEBUG:  search_length: %i\n",search_length);
    google = (u_char*)malloc(search_length +1);     
    strncpy((char*)google, (char*)g_start, search_length);
    google[search_length] = '\0'; //null terminator

1 个答案:

答案 0 :(得分:1)

Operator precedence表示

if(g_start = strstr(final_url, "q=") != NULL)

评估为

if(g_start = (strstr(final_url, "q=") != NULL))

会将10分配给g_start

您需要在该行的开头使用括号()来获取所需的评估顺序:

if((g_start = strstr(final_url, "q=")) != NULL)
// ^                                 ^

请注意,您的编译器应该已经警告过您。例如MSVC给出了

warning C4047: '=' : 'char *' differs in levels of indirection from 'int'