Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C初学者:字符串解析_C_String_Parsing - Fatal编程技术网

C初学者:字符串解析

C初学者:字符串解析,c,string,parsing,C,String,Parsing,我正在尝试分析以下HTTP响应: HTTP/1.1 200 OK Date: Tue, 06 Dec 2011 11:15:21 GMT Server: Apache/2.2.14 (Ubuntu) X-Powered-By: PHP/5.3.2-1ubuntu4.9 Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 48 Content-Type: text/html ��(�ͱ���I�O����H�����ч��

我正在尝试分析以下HTTP响应:

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:15:21 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

��(�ͱ���I�O����H�����ч��
                      �4�@�B�$���S
我想提取“48”和二进制内容

以下是我迄今为止所做的尝试:

  //char* str contains the response
  char * pch;
  printf ("Splitting response into tokens:\n");
  pch = strtok (str,"\r\n");
  while (pch != NULL)
  {
      printf ("%s\n",pch);
      pch = strtok (NULL, "\r\n");
  }
但我现在有点困了。。。非常感谢您的帮助


编辑:

以下是我迄今为止所做的工作:

char* pch;
char* pch2;
pch=strstr(buf,"Content-Length:");
pch2=strstr(pch,"\r\n");
我怎样才能得到这两个指针之间的位


编辑:解决方案:

        char* pch;
        char* pch2;
        pch=strstr(buf,"Content-Length:");
        int i=0;
        char contLen[20];
        for(i=0;i<20;i++){
                char next=pch[strlen("Content-Length:")+i];
                if(next=='\r' || next=='\n'){
                        break;
                }
                contLen[i]=next;
        }
        printf("%d\n",atoi(contLen));
char*pch;
char*pch2;
pch=strstr(buf,内容长度:);
int i=0;
char contLen[20];

对于(i=0;i为什么不搜索字符串
“Content Length:”
,然后从该点向前移动

您可以使用
strstrstr()
str
中查找点,然后将字符指针向前移动
strlen(“内容长度:”)
位置,然后使用
atoi()
读取值

不需要对整个字符串进行标记。

尝试以下操作:

const char* http_header = 
"HTTP/1.1 200 OK\r\n" \
"Date: Tue, 06 Dec 2011 11:15:21 GMT" \
"Server: Apache/2.2.14 (Ubuntu)\r\n" \
"X-Powered-By: PHP/5.3.2-1ubuntu4.9\r\n" \
"Vary: Accept-Encoding\r\n" \
"Content-Encoding: gzip\r\n" \
"Content-Length: 48\r\n" \
"Content-Type: text/html\r\n\r\n" \
"mydata";

// will point to start of the actual data that following the http header
char* pdata = strstr((char*)http_header,"\r\n\r\n");
// will point to start of 'Content-Length' header
char* pcontent = strstr((char*)http_header,"Content-Length:");
// get the length of the data
int value = atoi(pcontent + 15);

您可以检查,并且
CURLOPT_WRITEHEADER
选项我不想使用CURL。我使用套接字做所有事情…当然,您应该在使用它们之前检查pdata和pcontent是否有效…希望没有人输入“Content Length:-1”在他们的服务器字符串中?在内容长度:和实际值之间可能有空格,并且内容长度可能都是小写或大写。我猜还有更多。。。