- 论坛徽章:
- 0
|
代码如下
- fp = fopen(local_file, "a");
- if(!fp)
- {
- printf("create file error! %s\n", strerror(errno));
- return 0;
- }
- printf("\nThe following is the response header:\n");
- i=0;
- /* ........http...response */
- /*-----------reading header info--------------*/
- int status = 0;
- char size[1024]={0};
- char *len=0;
- long data_size=0;
- while((nbytes=read(sockfd,buffer,sizeof(buffer)))!=0)
- {
- if(status == 0)
- {
- printf("-----------------exec ---------\n");
- char *hp = buffer; // Start of header
- char *cp = 0;
- char *ep = hp + 1024; // End of string
- char *bp = 0; // Start of body
- char *lp = 0; // Start of content-length value
- char *kp = 0; // Start of connection value
- for (cp = hp; (bp == 0) && (cp < ep); ++cp)
- {
- if ((ep - cp > 16) && (strncasecmp(cp, "Content-Length: ", 16) == 0))
- {
- lp = cp + 16;
- while(*lp!='\r'&&i<sizeof(size))
- {
- size[i]=*lp;
- lp++;
- i++;
- }
- if(*lp=='\r')
- {
- size[i]='\0';
- }
- len=(char *)malloc(strlen(size));
- strncpy(len,size,strlen(size));
- data_size=(long)atoi(len);//get the file size
- }
- else if ((ep - cp > 12) && (strncasecmp(cp, "Connection: ", 12) == 0))
- {
- kp = cp + 12;
- }
- else if ((ep - cp > 4) && (strncmp(cp, "\r\n\r\n", 4) == 0))
- {
- bp = cp + 4;
- status =1;
- }
- else if ((ep - cp > 2) && (strncmp(cp, "\n\n", 2) == 0))
- {
- bp = cp + 2;
- status = 1;
- }
- }
- if(bp == 0&& status == 0)
- {
- continue;
- }
- /*----------read header info-------------*/
- char tmp[10240]={0};
- cp=bp;
- for(i=0;i<ep-cp&&bp<ep;i++,bp++)
- {
- tmp[i]=*bp;
- }
- if(fwrite(tmp,ep-cp,1,fp)) fflush(fp);
- continue;
- }
- else
- {
- /*-----------read body info--------------*/
- long file_size=0;
- struct stat f_stat;
- if( stat( local_file, &f_stat ) == -1 )
- {
- return -1;
- }
- file_size=(long)f_stat.st_size;
- if(file_size<=data_size)
- {
- if(fwrite(buffer,sizeof(buffer),1,fp))
- {
- fflush(fp);
- }
- else printf("failure........\n");
- }
- else
- {
- fclose(fp);
- break;
- }
- }
- }
复制代码
[ 本帖最后由 seawand_zhu 于 2007-9-11 11:32 编辑 ] |
|