I have the following code, which is my attempt to make a single string containing the stored HTTP header fields:
typedef struct _header {
char* name;
char* value;
} header;
const header headers[] = {
{ "Content-Type", "text/html" },
{ "Server", "testServer" }
};
int headerStringSize = sizeof(char) * 1024 + 1;
char* headerString = malloc(headerStringSize);
int i, headersLength = sizeof(headers) / sizeof(headers[0]);
for (i = 0; i < headersLength; ++i) {
header h = headers[i];
snprintf(headerString, headerStringSize, "%s: %s\r\n", h.name, h.value);
}
However, it doesn't work as snprintf
simply overwrites the contents of headerString
on each iteration, rather than appending at the correct char index. I am used to higher-level languages than C, so my problems are entirely down to my own ignorance. I would, therefore, greatly appreciate it if someone could show me the best way to achieve what I want.
strcpy()
andstrcat()
.headerString[0]=0;
before the loop andsnprintf(headerString + strlen(headerString), ....
in the loop.