Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I want to make copies of the exe 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 doesn’t copy the executable completely. See the size column in the following screenshot):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The executables not completely copied

Please help me to solve this problem.
Thanks.

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading