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:
Then recombine the name adding a random hex sequence (or maybe a counter?)
call
rename()on the new files.UPDATE
As noticed by Zack, rename will not fail if the new file exists, so after generating
newFilename, eitherstat(mind the race condition — see Zack’s other comment) oropen(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.