Your code is working as expected considering that strcat
appends the extension to the given string. You're using only one string, and so the extensions get stacked upon one another.
Here's one way to do this, amending your posted code which uses a single string for filename
:
size_t len = strlen(filename);
f1 = fopen(strcat(filename, ".dt1"), "wt");
filename[len] = '\0';
f2 = fopen(strcat(filename, ".dt2"), "wt");
filename[len] = '\0';
f3 = fopen(strcat(filename, ".dt3"), "wt");
Setting this index to \0
effectively truncates filename
back to the original string between calls.
Note that filename
must be large enough to contain the appended extensions - room for 4 additional characters - and that by doing this you'll lose the intermediate file names after opening each file.
Alternately, if your extensions will only differ in the last character:
size_t len = 0;
f1 = fopen(strcat(filename, ".dt1"), "wt");
len = strlen(filename);
filename[len - 1] = '2';
f2 = fopen(filename), "wt");
filename[len - 1] = '3';
f3 = fopen(filename, "wt");
The same caveats as above apply.
Note: this answer assumes that filename
has been allocated correctly and with sufficient space to store the string lengths being used, as mentioned above.