简体   繁体   中英

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:

  • facebook.png
  • instagram.png
  • twitter.png

I'd like to have them renamed to

  • facebook-a0b1c2.png
  • instagram-d3e4f5.png
  • twitter-a6b7c9.png

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM