C beginner: string parsing

Why don't you instead search for the string "Content-Length:", then from that point move forwards?

You can use strstr() to find the spot in str, then move the char pointer forward strlen("Content-Length:") positions, then read the value using atoi().

There is no need to tokenize the whole string.


Try this:

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);

Tags:

C

String

Parsing