Mattis Seehaus Mattis Seehaus - 1 year ago 161
C Question

Insert Integer in char array to use it in rename function

it´s long ago since i tried to code sth. but i´m looking for a simple way of iterating through some folders to rename the containing files.

i have folder which look like 'MORE0001', 'MORE0002' etc. They contain all one file with the same name 'Data'

What i want to do is to rename all containing files to 'data.dat' (and maybe to find a way to extract the files out of the folders..)

so this is what it looks like:

for (int i=0; i<10;i++){

char oldname[]= "directory/MORE0001/data";
char newname[]= "directory/MORE0001/data.dat";



this works pretty fine, but i want to change the
within the for-loop to

hope you guys can help me.. i did not find an answer yet to this simple question

Answer Source

Use sprintf:

char oldname[100];
char newname[100];
sprintf(oldname, "directory/MORE%04d/data", i);
sprintf(newname, "directory/MORE%04d/data.dat", i);

The 100 should be big enough to hold the pathname. If it's too short, your program will crash or (worse) rename your files into having unusable names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download