Kirils Surovovs Kirils Surovovs - 2 months ago 15
C++ Question

Cannot copy a file and then execute it in c++

I want to copy a file and then execute it using c++. Maybe it is not smart to use c++ for the task that can be accomplished with simple scripts, but I just want the program to do all things at once. Anyway, the code is looking like

#include <cstdlib>
#include <iostream>
#include <fstream>
void input ()
{
std::ifstream src("path-to-file\\myFile.exe", std::ios::binary);
std::ofstream dst("myFile.exe", std::ios::binary);
dst << src.rdbuf();
system("myFile.exe -some -parameters");
}
int main ()
{
input ();
return 0;
}


(I included here so many lines for this code to be easier "copy-pastable" for you). When I run it, I see the error message:

The process cannot access the file because it is being used by another process.


I have not found any solution to this problem at this site and on the Internet. Only post I found was about "closing the file handle" as it was written here. But as a very beginner, I do not understand how to do it in this particular situation. Can anyone please help?

Answer

The problem is that don't close the file. You have at least three ways to do this.

One is to close it explicitly with dst.close(); before the system call.

void input ()
{
    std::ifstream  src("path-to-file\\myFile.exe", std::ios::binary);
    std::ofstream  dst("myFile.exe",   std::ios::binary);
    dst << src.rdbuf();
    dst.close();
    system("myFile.exe -some -parameters");
}

A cleaner way would be to put the opening and copying in a scope, so that the variable dst goes out of scope and its destructor is called; it will then be closed.

void input ()
{
    {
        std::ifstream  src("path-to-file\\myFile.exe", std::ios::binary);
        std::ofstream  dst("myFile.exe",   std::ios::binary);
        dst << src.rdbuf();
    }
    system("myFile.exe -some -parameters");
}

Or, put the opening and closing in a separate function, which is what I would have done in this case. Then, the body of the function is the scope. Maybe over-engineered if you only need to do it once.