请参阅以下代码:
int main() {
char a[50];
FILE *fp;
fp = fopen("test1.txt", "w");
sprintf(a,"jigar %d \n", 3);
fprintf(fp,"jigar %d \n", 3);
sprintf(a,"patel %d \n", 2);
fprintf(fp,"patel %d \n", 2);
printf("%s", a);
}
在这里,使用fprintf
,我可以在文件中写入
jigar 3
patel 2
我想要相同的功能,我打印的任何东西都放在一个字符缓冲区中。
但是使用sprintf
给我提供了缓冲区
patel 2
我有这么多这样的打印,我想添加到一个字符缓冲区,然后我需要返回给应用程序,那么如何在中获得它最简单和最快的方式呢?
发布于 2012-04-24 17:19:09
sprintf()
返回打印的字符数。
只需在下一次写入时使用该数字...
int i;
char a[50];
char *ap = a;
for (i = 5; i < 15; i++) {
ap += sprintf(ap, "%d ", i);
}
printf("%s\n", a); /* "5 6 7 8 9 10 11 12 13 14 " */
但要确保不会导致任何缓冲区溢出。
发布于 2018-06-14 04:56:29
这个想法是给一个指向缓冲区基地址的指针+一个偏移量。当你追加的时候,偏移量会变大。
通过使用strlen,可以获得当前“字符串”的长度。为了避免缓冲区溢出,我们可以添加额外的逻辑,以检查当前“字符串”+“新字符串”是否小于缓冲区的大小。
size_t offset = strlen(text);
sprintf(&(text[offset]), "This is how You append using sprintf");
循环中的示例:
char text[255];
text[0] = '\0';
for(int i = 0 ; i < 10 ; i++) {
size_t offset = strlen(text);
sprintf(&(text[offset]), "%d,", i);
}
与其他stackoverflow用户建议的一样,您还可以使用snprintf,它还可以为您提供缓冲区溢出保护。
append函数可能如下所示:
void append(char *text, int maxSize, char *toAppend) {
size_t offset = strlen(text);
snprintf(&(text[offset]), maxSize, "%s", toAppend);
}
发布于 2016-02-18 20:12:58
如果您使用的是与POSIX兼容的系统,那么可以看看fmemopen(3)
或open_memstream(3)
#include <assert.h>
#include <stdio.h>
int main(void)
{
char buf[128] = { 0 };
FILE *fp = fmemopen(buf, sizeof(buf), "w");
assert(fp);
fprintf(fp, "Hello World!\n");
fprintf(fp, "%s also work, of course.\n", "Format specifiers");
fclose(fp);
puts(buf);
}
https://stackoverflow.com/questions/10295031
复制相似问题