我已经定义了一个char
带有预定义HTTP发布字符串的数组,如下所示:
char header[] = "POST /api/add HTTP/1.1\r\nHost: xxxxxxx:3000\r\nContent-Type: application/octet-stream; charset=utf-8\r\nContent-Length: 500\r\nName: ";
strcat(header, strDevicename); \\
strcat(header, "\r\n\r\n");
其中strDevicename
是char
变量名改变每个请求。问题是,当我运行它的第一次,这是工作,但该覆盖掉后Name
用a96ed5ÿÿa96ed58e8355
。
在HTTP发布标头中使用C语言添加具有一个实时更改变量的两个字符串的最佳方法是什么?
问题是您正在[str]串联到一个header
没有多余空间的数组()(C数组的大小无法更改)。
snprintf
可能更适合这里。
如果您知道的最大可能长度strDevicename
,则可以使用固定大小的缓冲区:
const char header[] = "POST /api/add HTTP/1.1\r\nHost: xxxxxxx:3000\r\nContent-Type: application/octet-stream; charset=utf-8\r\nContent-Length: 500\r\nName: ";
const char tail[] = "\r\n\r\n";
char buf[(sizeof header - 1) + MAX_DEV_LENGTH + (sizeof tail - 1) + 1];
/* sizeof would count the null byte in header & tail arrays. */
snprintf(buf, sizeof buf, "%s%s%s", header, strDevicename, tail);
如果strDevicename
长度未知,则可以使用asprintf
(GNU函数):
char *buf = NULL;
if (asprintf(&buf, "%s%s%s", header, strDevicename, tail) == -1) {
/* handle memory allocation failure */
}
...
free(buf);
如果您asprintf
不可用,则可以使用分配自己足够的内存(与上面一样)malloc
,然后使用snprintf
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句