Reputation: 13
I am trying to make a program then open it by using this code.
//Make the file
std::ifstream src(a, std::ios::binary);
std::ofstream dst(b, std::ios::binary);
dst << src.rdbuf();
//Execute it
Execute((LPCTSTR)b.c_str());
Function Execute:
bool Execute(LPCTSTR Process)
{
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
ZeroMemory(&sInfo, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
ZeroMemory(&pInfo, sizeof(pInfo));
if (!CreateProcess(Process, "open", NULL, NULL, false, 0, NULL, NULL, &sInfo, &pInfo))
{
return 0;
}
return 1;
}
I have tested making the file and it works when i open the file manualy nothing goes wrong. I tried the execute function and it works fine not a single problem. But when I combined those 2 for some reason it will not execute.
If somebody could tell me why and/or how to fix it that would be very helpful.
Thank you.
Upvotes: 0
Views: 267
Reputation: 6240
Might as well type the full answer. Basically if the ofstream
is not closed, the createProcess
fails. Here is the sample code to test:
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
bool Execute(LPCTSTR Process)
{
STARTUPINFO sInfo = {};
sInfo.cb = sizeof(sInfo);
PROCESS_INFORMATION pInfo = {};
return CreateProcess(Process, NULL, NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &sInfo, &pInfo);
}
int main()
{
std::wstring src_name(L"C:\\Windows\\system32\\notepad.exe");
std::wstring dst_name(L"C:\\Users\\KK\\Desktop\\mynotepad.exe");
std::ifstream src(src_name, std::ios::binary);
std::ofstream dst(dst_name, std::ios::binary);
dst << src.rdbuf();
src.close();
dst.close(); // has to be closed before execution
if (!Execute(dst_name.c_str()))
{
std::cout << "ERROR: " << GetLastError() << std::endl;
}
return 0;
}
Commenting out dst.close();
produces error.
Upvotes: 1
Reputation: 13
Question is solved and it turned out to be really simple which was that i just had to close the stream as "Killzone Kid" pointed out.
Upvotes: 0