0

我正在努力寻找 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
4

1 回答 1

1

运算符优先级意味着

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

被评估为

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

将分配1或分配0g_start.

您需要()在行首使用括号来获得所需的评估顺序:

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

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

warning C4047: '=' : 'char *' differs in levels of indirection from 'int'
于 2013-11-14T22:36:27.863 回答