Chinaunix首页 | 论坛 | 博客
  • 博客访问: 389637
  • 博文数量: 32
  • 博客积分: 6015
  • 博客等级: 准将
  • 技术积分: 1320
  • 用 户 组: 普通用户
  • 注册时间: 2005-03-06 21:06
文章分类

全部博文(32)

文章存档

2010年(11)

2009年(7)

2008年(14)

我的朋友

分类: C/C++

2010-04-26 15:34:19

不多说,直接上url解析代码

int
parseUrl(char *url,
         char **serverstrp,
         int *portp,
         char **pathstrp)
{
    char buf[256];
    int serverlen, numread=0;

    /* go through the url */
    /* reset url to point PAST the http:// */
    /* assume it''s always 7 chars! */
    url = url+7;

    /* no http:// now... server is simply up to the next / or : */
    sscanf(url, "%255[^/:]", buf);/* max scan is 255 char,and end to '/' or ':' */
    serverlen = strlen(buf);
    *serverstrp = (char *)malloc(serverlen+1);
    strcpy(*serverstrp, buf);

    if(url[serverlen] == ':')
    {
        /* get the port */
        sscanf(&url[serverlen+1], "%d%n", portp, &numread);
        /* add one to go PAST it */
        numread++;
    }else{
        *portp = 80;
    }
    /* the path is a pointer into the rest of url */
    *pathstrp = &url[serverlen+numread];
    return 0;
}


2个sscanf的妙用,极大简化 了解析代码。强大。
阅读(741) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~