Jack Bauer
Jack Bauer

Reputation: 45

C format string when writing to file

I'm having a bit of noob confusion how to use a formated string when writing to a file, and more in general I guess about 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 is testing for fprintf...\n");
    fputs("This is testing for fputs...\n", fp);
    fclose(fp);
}

I get a segmentation fault when trying the formatted saveToPath, but if I use a plain string const char* like "/Path/To/My/File.txt" it works.

Upvotes: 1

Views: 8989

Answers (3)

finesse
finesse

Reputation: 117

you should pre-alloc memory for saveToPath; char saveToPath[100] pre-alloc 100 bytes in stack. However, for more safety and generic usage, I suggest you coding as follows:

const char *prefix = "/path/to/myfile";
const char *suffix = ".txt";
// here, 1 more bit for the terminal '\0'
char *saveToPath = (char *)calloc(sizeof(char), strlen(prefix) + strlen(suffix) + 1);
sprintf(saveToPath, "%s%s", prefix, suffix);
FILE *fp = fopen(...);
...

for more safety coding style, try to use snprintf instead of sprintf

Upvotes: 0

Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

char *saveToPath only declares a pointer to a char. It doesn't allocate any memory to save your characters.

You could either allocate memory on the stack:

char saveToPath[1024];

or you could allocate memory on the heap if you don't know at compile how much memory you would need:

char *saveToPath = malloc(nsize * sizeof *saveToPath);

Remember to check for buffer overflow before using sprintf():

if(nsize < strlen("/Path/To/My/File") + strlen(exts) + 1)
    /* error - BUFFER NOT ENOUGH*/

sprintf(saveToPath, "/Path/To/My/File%s", exts);

You may use snprintf(), but remember it's non-standard and may come back to bite you in the back if you use it in a program intended to be portable.

Since you said you are inexperienced in C, I suggest you make it a habit to write portable code.

Upvotes: 2

Sajith Eshan
Sajith Eshan

Reputation: 696

Allocate memory to your saveToPath variable

e.g.

char saveToPath[100];

Also, consider using snprintf to avoid buffer overflows

e.g.

snprintf(saveToPath, 100 ,"/Path/To/My/File%s", exts);

So that you make sure you don't write anything beyond 100 bytes allocated for saveToPath

Upvotes: 2

Related Questions