Search code examples
cstringstrcat

C: creating new file extensions based on a filename


I would like to name output files based on a base filename with a different extension. In C psuedo-code:

a_file = fopen(filename + ".dt1","wt");
b_file = fopen(filename + ".dt2","wt");
c_file = fopen(filename + ".dt3","wt");

I tried following this example using strncat, but my program keeps appending to filename.

f1=fopen(strcat(filename,".dt1"),"wt");
f2=fopen(strcat(filename,".dt2"),"wt");
f3=fopen(strcat(filename,".dt3"),"wt");

This outputs:

filename.dt1
filename.dt1.dt2
filename.dt1.dt2.dt3

I need the end result to look like:

filename.dt1
filename.dt2
filename.dt3

Solution

  • Kind of a pain with standard C libs, but this is the way I would do it.

        char *fn = malloc(strlen(filename+5)); // Allocate a string with enough space
                                               // for the extensions.
    
        sprintf(fn, "%s.dt1", filename);       // Copy the name with extensions into fn.
        a_file = fopen(fn,"wt");               //
        sprintf(fn, "%s.dt2", filename);       //
        b_file = fopen(fn,"wt");               //
        sprintf(fn, "%s.dt3", filename);       //
        c_file = fopen(fn,"wt");               //
    
        free(fn); // Free the memory gained from malloc.