printf - C format string when writing to file -


i'm having bit of noob confusion how use formated string when writing file, , more in general guess sprintf.

#include <stdio.h>  int main(int argc, char* argv[])  {     file *fp;     const char *exts = ".txt";     char *savetopath;      sprintf(savetopath, "/path/to/my/file%s", exts);      fp = fopen(savetopath, "w+");     fprintf(fp, "this testing fprintf...\n");     fputs("this testing fputs...\n", fp);     fclose(fp); } 

i segmentation fault when trying formatted savetopath, if use plain string const char* "/path/to/my/file.txt" works.

allocate memory savetopath variable

e.g.

char savetopath[100]; 

also, consider using snprintf avoid buffer overflows

e.g.

snprintf(savetopath, 100 ,"/path/to/my/file%s", exts); 

so make sure don't write beyond 100 bytes allocated savetopath


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -