ILikeTacos
ILikeTacos

Reputation: 18666

how to rename filenames in C

I wrote this piece of code that lists all JPG files in the current directory,

#include <string.h>
#include <stdio.h>
#include <dirent.h> 
int main() {
    char *ptrToSubString;
    char fileName[100];
    DIR *dir;
    struct dirent *ent;
    dir = opendir(".");
    if (dir != NULL) {
            while((ent = readdir(dir)) != NULL) {
                   strcpy(fileName,ent->d_name);
                   ptrToSubString = strstr(fileName,".jpg");
                   if (ptrToSubString != NULL) {
                       printf("%s",ent->d_name);
                   } else {
                      continue;
                   }
            }
            closedir(dir);
    } else {
            perror("");
            return 5;
 }
return 0;
}

but I'd like to add the functionality to rename the files to a unique filename, or append a unique identifier to the filename.

For instance, If the program lists the following filenames:

I'd like to have them renamed to

any idea on how to achieve this? Any help will be greatly appreciated! Thank you!

Upvotes: 2

Views: 1483

Answers (2)

LSerni
LSerni

Reputation: 57388

Split the name:

*(ptrToSubString++) = 0x0;

Then recombine the name adding a random hex sequence (or maybe a counter?)

snprintf(newFilename, SIZE_OF_NEWFILENAME_BUFFER,
     "%s-%06x.%s", fileName, rndhex, ptrToSubString);

call rename() on the new files.

UPDATE

As noticed by Zack, rename will not fail if the new file exists, so after generating newFilename, either stat (mind the race condition -- see Zack's other comment) or open(newFilename, O_WRONLY|O_CREAT|O_EXCL, 0600) must be used to verify the new name isn't in use. If it is, generate a new random and repeat.

Upvotes: 3

Rivasa
Rivasa

Reputation: 6740

Well there is a rename function found in stdio.h. You could use that like this:

/* rename example */
#include <stdio.h>

int main (){
    int result;
    char oldname[] ="oldname.txt";
    char newname[] ="newname.txt";
    result= rename( oldname , newname );
    if ( result == 0 )
        puts ( "File successfully renamed" );
    else
        perror( "Error renaming file" );
    return 0;
}

Just adapt this to your needs. You can also read up more on it here.

Upvotes: 1

Related Questions