I have a buffer that contains the HTTP header, which contains the Content-Length
string indicating how big the file is that needs to be downloaded.
I am looking to write a generic function for parsing a substring and eventually a value that needs to be converted to an int
from a string.
The following approach seems to work but seems more like a "brute-force" approach. Any better ideas?
void parse(char *src, char *dst, const char *firstKey, const char *secKey)
{
char *start = strstr(src, firstKey) + 2;
char *end = strstr(start, secKey);
size_t bytes = end - start;
memcpy(dst, start, bytes);
}
int main()
{
char httpHeader[] = {72, 84, 84, 80, 47, 49, 46, 49, 32, 50, 48, 49, 32, 67, 114, 101, 97, 116, 101, 100, 13, 10, 68, 97, 116, 101, 58, 32, 77, 111, 110, 44, 32, 49, 55, 32, 74, 97, 110, 32, 50, 48, 50, 50, 32, 50, 49, 58, 53, 56, 58, 52, 51, 32, 71, 77, 84, 13, 10, 83, 101, 114, 118, 101, 114, 58, 32, 65, 112, 97, 99, 104, 101, 47, 50, 46, 52, 46, 50, 57, 32, 40, 85, 98, 117, 110, 116, 117, 41, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110, 103, 116, 104, 58, 32, 48, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 58, 32, 116, 101, 120, 116, 47, 104, 116, 109, 108, 13, 10, 13, 10};
/*
what httpHeader above stores:
HTTP/1.1 201 Created
Date: Mon, 17 Jan 2022 21:58:43 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Length: 0
Content-Type: text/html
*/
char dst[100] = {0};
parse(httpHeader, dst, "Content-Length", "\n"); // dst => Content-Length: 0
char dst1[100] = {0};
parse(dst, dst1, ":", "\r");
// get the int value
int contentLenVal = atoi(dst1);
printf ("dst: %s\ndst1: %s\n\nContent value: %d\n", dst, dst1, contentLenVal);
}