c++fstream

How to make copies of the executable itself in C++?


I want to make copies of an executable file itself multiple times.

I tried the following code:

#include <fstream>
#include <string>

int main() {
    std::ifstream from("main.exe", std::ios::binary);
    auto buf { from.rdbuf() };

    for(int x { 0 }; x <= 10; ++x) {
        std::string name { "main" + std::to_string(x) + ".exe" };

        std::ofstream out(name, std::ios::binary);
        out << buf;
        out.close();
    }

    from.close();
    return 0;
}

But it doesn't work as I expected (It does not copy the executable repeatedly. See the size column in the following screenshot):

The executables not completely copied

How do I solve this problem?


Solution

  • Reading from the input file stream buffer consumes the data. You need to reset the stream to the start after copying the file:

    ...
    
    for (int x{ 0 }; x <= 10; ++x) {
        std::string name{ "main" + std::to_string(x) + ".exe" };
    
        std::ofstream out(name, std::ios::binary);
        out << buf;
        out.close();
        from.seekg(0, std::ios::beg); // need to go back to the start here
    }
    
    ...
    

    You could simply use the std::filesystem standard library functionality for this though:

    
    int main() {
        std::filesystem::path input("main.exe");
    
        for (int x{ 0 }; x <= 10; ++x) {
            std::filesystem::path outfile("main" + std::to_string(x) + ".exe");
    
            std::filesystem::copy_file(input, outfile, std::filesystem::copy_options::overwrite_existing);
        }
    
        return 0;
    }