Search code examples
c++filesystemsc++17fstream

std::fstream / std::filesystem create file with duplicate number


I want to create a file with a number at the end of the file : filename ( number goes here ).txt. The number will tell me if there were duplicates of the file in the directory the file was created : filename.txt .

Example : helloworld (1).txt

Windows also has this functionality when trying to create a file duplicate. Is there way I could do this in C++ 17 ?


Solution

  • Since no one is giving me any answers, I decided to spend some time on this function that does what I want , and answer my own question , its in C++ 17 for anyone who thinks this is useful :

    #include <filesystem>
    #include <regex>
    #include <fstream>
    #include <string>
    
    namespace fs = std::filesystem;
    
    // Just file "std::ostream::open()" except it handles duplicates too
        void create_file_dup(std::string path)
        {
            // Check if file doesnt have duplicates
            if (!fs::exists(path)) {
                std::ofstream(path);
                return;
            }
    
            // Get filename without path
            std::string filename = (fs::path(path).filename()).string();
    
            // Since its already a duplicate add "(1)" inbetween the basename and extension
            filename = (fs::path(filename).stem()).string() + " (1)" + (fs::path(filename).extension()).string();
    
            // Get file's parent directory
            std::string parent = (fs::path(path).parent_path()).string();
    
    
            // Loops to check for more duplicates
            for (int dup_count = 2;!fs::exists(parent + filename);dup_count++) {
    
                std::string dup_c = "(" + std::to_string(dup_count);      // old number
                dup_c + ")";
    
                std::string dup_cn = "(" + std::to_string(dup_count + 1);   // new number 
                dup_cn + ")";
    
                filename = std::regex_replace(filename, std::regex(dup_c), dup_cn); // increments : '(1)' -> '(2)'
            }
    
            // We have found the how many duplicates there are , so create the file with the duplicate number
            std::ofstream(parent + filename);
            return;
        }