0

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?

Community
  • 1
  • 1
  • 6
    You forgot to close the file before executing. – πάντα ῥεῖ Oct 03 '16 at 11:19
  • The file will get closed when its "handle" goes out of context, and in your case, this hasn't happened. You need to close it yourself, enclose the opening and copying in a scope with `{` and `}`, or do do the system call after the copying function exits. –  Oct 03 '16 at 11:21
  • 1
    Try: `dst.close();`. It may be worth *reading the instructions* before using a class like [std::ofstream](http://en.cppreference.com/w/cpp/io/basic_ofstream). – Galik Oct 03 '16 at 11:23
  • We have no idea, which line of code produces the error, or how you even observe that error. Learn to use a debugger. It's the tool you'll be using more frequently than anything else. – IInspectable Oct 03 '16 at 11:25
  • @Boris, thank you very much! Enclosing in braces perfectly helped me! – Kirils Surovovs Oct 03 '16 at 11:31

1 Answers1

2

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.