Dave Engineer
Dave Engineer

Reputation: 386

%d inside variable filename in C

Making a program that logs data. I want it to start a new file with an incremented integer every time it reaches a set limit of file space (in bytes).

Everything works fine until I use:

file_name = ("Data%d.bin",fileIncrement);

Instead of:

file_name = "Data.bin";

When I replace the above, the software no longer writes to a file.

Here is the function in question:

    char *file_name;
    static int fileSize = 0;  //bytes
    static int fileIncrement = 1;

    //Set file name
    if (fileSize == 0)
    {
        file_name = ("Data%d.bin",fileIncrement);
        ++fileIncrement;
    }

    fileSize += size;

    if (fileSize >= 1024)
    {
        fileSize = 0;
    }

    // Write to file system
    ...
    ...
    ...
}

I initially tried with a time stamp, but that didn't work and brought it back to basics.

Upvotes: 0

Views: 1468

Answers (2)

The file path for fopen, open etc... is a string. You can build that string, e.g. using snprintf, like e.g.

char filepath[256];
snprintf (filepath, sizeof(filepath), "Data%d.bin", fileIncrement);
FILE * fil = fopen(filepath, "w");
if (!fil) { perror(filepath); exit(EXIT_FAILURE); };

Read the documentation of fopen(3), perror(3), exit(3), snprintf(3) -and of every function you are using-; you'll need to add some more #include directives.

Avoid using  sprintf (but use snprintf) because you should be scared of buffer overflow and other undefined behavior.

You might even test the result of snprintf to be sure it is succeeding and fits in filepath.

At compilation time, enable debugging information and all warnings (i.e. compile with gcc -Wall -g if using GCC). Then use the debugger (e.g. gdb)

Upvotes: 7

unwind
unwind

Reputation: 399803

Many people seem to think that just because you can do

printf("%d", 4711);

to print an integer, you should be able to use ("%d", 4711) anywhere to format an integer into a string.

This is not true, and not how C works. In C, functions do this kind of work, and the function here is of course printf(), which means "print, formatted".

You can use another function to do the formatting without the printing, like snprintf():

char buf[32];

snprintf(buf, sizeof buf, "Data%d.bin", fileIncrement);

Then pass buf to the function doing the opening, i.e. fopen(buf, "rb") or whatever.

Upvotes: 7

Related Questions