Comment append des chaînes en utilisant sprintf?

Je suis confronté à un sérieux problème avec sprintf.

Supposons que mon extrait de code soit:

sprintf(Buffer,"Hello World"); sprintf(Buffer,"Good Morning"); sprintf(Buffer,"Good Afternoon"); . . . 

Une centaine de sprints ….

Si je fais comme ça, il sera écrasé.

Comment puis-je éviter d’écraser en utilisant sprintf. Si je donne un printf à la fin, je veux voir toutes les lignes.

Vous avez besoin:

 sprintf(Buffer,"Hello World"); sprintf(Buffer + strlen(Buffer),"Good Morning"); sprintf(Buffer + strlen(Buffer),"Good Afternoon"); 

et bien sûr, votre tampon doit être assez gros.

 int length = 0; length += sprintf(Buffer+length, "Hello World"); length += sprintf(Buffer+length, "Good Morning"); length += sprintf(Buffer+length, "Good Afternoon"); 

Voici une version avec une certaine résistance aux erreurs. C’est utile si vous ne vous souciez pas des erreurs qui surviennent tant que vous pouvez continuer votre chemin quand elles le sont.

 int bytes_added( int result_of_sprintf ) { return (result_of_sprintf > 0) ? result_of_sprintf : 0; } int length = 0; length += bytes_added(sprintf(Buffer+length, "Hello World")); length += bytes_added(sprintf(Buffer+length, "Good Morning")); length += bytes_added(sprintf(Buffer+length, "Good Afternoon")); 

Pour plus de sécurité (buffer overflow), je recommande d’utiliser snprintf ()

 const int MAX_BUF = 1000;
 char * Buffer = malloc (MAX_BUF);

 int length = 0;
 length + = snprintf (longueur du tampon +, MAX_BUF-length, "Hello World");
 longueur + = snprintf (longueur tampon + longueur MAX_BUF-longueur, "bonjour");
 longueur + = snprintf (longueur tampon + longueur, MAX_BUF-longueur, "bon après-midi");

Un wrapper snprintf() pour snprintf() :

 size_t snprintfcat( char* buf, size_t bufSize, char const* fmt, ...) { size_t result; va_list args; size_t len = strnlen( buf, bufSize); va_start( args, fmt); result = vsnprintf( buf + len, bufSize - len, fmt, args); va_end( args); return result + len; } 

Pourquoi voulez-vous utiliser sprintf pour la concaténation de chaînes quand il existe des méthodes spécifiques à ce dont vous avez besoin, telles que strcat et strncat ?

Utilisez la valeur de retour de sprintf()

 Buffer += sprintf(Buffer,"Hello World"); Buffer += sprintf(Buffer,"Good Morning"); Buffer += sprintf(Buffer,"Good Afternoon"); 

Est-ce que vous ajoutez simplement des littéraux de chaîne? Ou allez-vous append différents types de données (ints, floats, etc.)?

Il serait peut-être plus facile d’abstraire cette fonction dans sa propre fonction (ce qui suit suppose que C99):

 #include  #include  #include  int appendToStr(char *target, size_t targetSize, const char * ressortingct format, ...) { va_list args; char temp[targetSize]; int result; va_start(args, format); result = vsnprintf(temp, targetSize, format, args); if (result != EOF) { if (strlen(temp) + strlen(target) > targetSize) { fprintf(stderr, "appendToStr: target buffer not large enough to hold additional ssortingng"); return 0; } strcat(target, temp); } va_end(args); return result; } 

Et vous l’utiliseriez comme ça:

 char target[100] = {0}; ... appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159); appendToStr(target, sizeof target, "blah blah blah"); 

etc.

La fonction renvoie la valeur de vsprintf , qui dans la plupart des implémentations est le nombre d’octets écrits dans la destination. Il y a quelques trous dans cette mise en œuvre, mais cela devrait vous donner quelques idées.

Je trouve que la méthode suivante fonctionne bien.

 sprintf(Buffer,"Hello World"); sprintf(&Buffer[strlen[Buffer]],"Good Morning"); sprintf(&Buffer[strlen[Buffer]],"Good Afternoon"); 

Je pense que vous recherchez fmemopen(3) :

 #include  #include  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); return 0; } 

Si le stockage dynamic est plus adapté à votre cas d’utilisation, vous pouvez suivre l’excellente suggestion de Liam concernant l’utilisation de open_memstream(3) :

 #include  #include  #include  int main(void) { char *buf; size_t size; FILE *fp = open_memstream(&buf, &size); assert(fp); fprintf(fp, "Hello World!\n"); fprintf(fp, "%s also work, of course.\n", "Format specifiers"); fclose(fp); puts(buf); free(buf); return 0; } 

Vous pouvez utiliser la ligne simple ci-dessous pour append des chaînes dans un tampon:

 sprintf(Buffer,"%s %s %s","Hello World","Good Morning","Good Afternoon"); 

Utilisez strcat http://www.cplusplus.com/reference/cssortingng/strcat/

 int main () { char str[80]; strcpy (str,"these "); strcat (str,"ssortingngs "); strcat (str,"are "); strcat (str,"concatenated."); puts (str); return 0; } Output: these ssortingngs are concatenated. 

J’écris une chaîne de variable dynamic de support de fonction append, comme PHP str append: str. str. … etc.

 #include  #include  #include  #include  int str_append(char **json, const char *format, ...) { char *str = NULL; char *old_json = NULL, *new_json = NULL; va_list arg_ptr; va_start(arg_ptr, format); vasprintf(&str, format, arg_ptr); // save old json asprintf(&old_json, "%s", (*json == NULL ? "" : *json)); // calloc new json memory new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char)); strcat(new_json, old_json); strcat(new_json, str); if (*json) free(*json); *json = new_json; free(old_json); free(str); return 0; } int main(int argc, char *argv[]) { char *json = NULL; /* str_append(&json, "name: %d, %d, %d", 1, 2, 3); str_append(&json, "sex: %s", "male"); str_append(&json, "end"); str_append(&json, ""); str_append(&json, "{\"ret\":true}"); */ int i; for (i = 0; i < 100; i++) { str_append(&json, "id-%d", i); } printf("%s\n", json); if (json) free(json); return 0; } 

PETIT EXEMPLE DE CODE COMPLET

Utilisation de la bibliothèque standard stdio standard uniquement

(et pas de soucis à propos de la taille du vecteur de chars depuis les “limites” du sprintf , cool hun? !!):

 #include  char c[]=""; int main() { int i=0; i+=sprintf(c+i,"Sergio "); i+=sprintf(c+i,"Mcfly "); i+=sprintf(c+i,"NY-USA "); i+=sprintf(c+i,"bla bla blahh...455453853;-)"); printf("%s",c); } 

SORTIE: Sergio Mcfly NY-USA bla bla blahh … 455453853 😉

En utilisant strcat ( buffer , ” Your new ssortingng...here “), en option.

Qu’en est-il de:

 char s[100] = ""; sprintf(s, "%s%s", s, "s1"); sprintf(s, "%s%s", s, "s2"); sprintf(s, "%s%s", s, "s3"); printf("%s", s); 

Mais prenez en compte les éventuels sur-stream de mémoire tampon!