how to get append mode in sprintf()

2020-07-16 03:21发布

问题:

See this code:

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);
}

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.

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?

回答1:

sprintf() returns the number of characters printed.

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.



回答2:

The idea is to give sprintf the pointer to the base address of your buffer + an offset. The offset gets bigger while you are appending.

By using strlen it is possible to get the lenght of the current 'string'.To avoid a buffer overflow, we could add extra logic in order to check if the current 'string' + 'the new string' is less than the size of the buffer.

size_t offset = strlen(text);
sprintf(&(text[offset]), "This is how You append using sprintf");

Example within a loop:

char text[255];
text[0] = '\0';
for(int i = 0 ; i < 10 ; i++) {
    size_t offset = strlen(text);
    sprintf(&(text[offset]), "%d,", i);
}

As from other stackoverflow users suggested, you could also use snprintf, which would give you also buffer overflow protection.

An append function could look like this:

void append(char *text, int maxSize, char *toAppend) {
  size_t offset = strlen(text);
  snprintf(&(text[offset]), maxSize, "%s", toAppend);
}  


回答3:

If you're on a POSIX-compatible system, have a look at fmemopen(3) or 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);
}


标签: c string printf