如何在 sprintf() 中获得追加模式 [英] how to get append mode in sprintf()

查看:47
本文介绍了如何在 sprintf() 中获得追加模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看此代码:

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,我可以在文件中写入

Here, using fprintf, I can write in file

jigar 3 
patel 2 

在我想要的相同功能的地方,我在一个字符缓冲区中打印的内容.

where same functionality I want where what ever I print that goes in one char buffer.

但是使用 sprintf 给了我缓冲区

but using sprintf gives me on buffer

patel 2 

我有很多这样的打印,我想在一个字符缓冲区中添加它们,然后我需要将它返回给应用程序,那么如何以最简单和最快的方式获取它?

I have so many such print which I want to add in one char buffer and then I need to return it to application so how to get it in simplest and fastest way this?

推荐答案

sprintf() 返回打印的字符数.

下次写入时只需使用该号码...

Just use that number for the next write ...

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 " */

请确保您不会导致任何缓冲区溢出.

Make sure you don't cause any buffer overflows though.

这篇关于如何在 sprintf() 中获得追加模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆