Copying files with appended file names


I’m attempting to implement a feature that allows any audio files that are imported into my application to be copied into my working directory but only if the audio files don’t already exist there. Below is an example of my code:

void MyClass::importAudioFile(File audioFile)
    if (audioFile != File::nonexistent)
        //create a new file based on the imported file's name and the path of the working directory
        File audioFileCopy (File::getCurrentWorkingDirectory().getFullPathName() + "/" + audioFile.getFileName());
        if (audioFileCopy.existsAsFile() == false) //if it doesn't yet exist...
            //...copy the imported audio file into the newly created file
        else if (audioFileCopy.existsAsFile() == true && audioFile.hasIdenticalContentTo(audioFileCopy) == false) 
        //if the file already exists (in terms of file name) but they aren't the same file in terms of content...
            //... copy the imported file but with different name
            audioFileCopy = audioFileCopy.getNonexistentSibling();
        //else, the imported file already exists in the directory so no new files need to be added

This is working great in that if a duplicate audio file is imported into my application it won’t get copied into my working directory, but if an audio file with an existing name is imported but their contents don’t match, the file will be copied with with a bracketed number appended to the end of the file name.

However, if I import an audio file which is a duplicate of one of the existing files with an appended bracketed number, the current algorithm does not prevent a new file being created. What would be the best way to go about implementing this, so that any imported files are checked against not just it’s file name but any appended version of it too?

I Hope I’ve explained that clear enough!


You need to use regex, like String::matchesWildcard() or you can put all the duplicates in a special folder.


So I would need to do something along the lines of:- search through the directory and look for file names that match using String::matchesWildcard(), check the contents against any matching files using hasIdenticalContentTo(), and only copy the file into the directory if all calls of hasIdenticalContentTo() equal false.
Does that sound appropriate?


After a bit of digging I found that the File::findChildFiles() method is what I needed. I used this function to find any file’s with a matching wildcard pattern, and then used the File::hasIdenticalContentTo() method to check against each of these matching files for a true duplicate.