0

I have a use case where I need to open MyProg.exe after it starts, make some edits and store it again replacing itself. We used to call this self-modifying code which got dubbed as seriously bad coding. However, I do have a real white-hat use case and would like to do just that.

This code fails at open:

std::fstream inOutFile;
inOutFile.open( exePathName, std::ios_base::in | std::ios_base::out | std::ios_base::binary );
if( inOutFile.is_open() )
{ …

As a test to see if it can be done with ordinary commands, I created MyTest.exe program, ran it from a command prompt, and with it running copied MyText.exe from another folder on top of the MyText.exe that was running. No problem, so I know there are some system file commands that will make it work. I was just hoping to use portable ISO c++ idioms where I can. Any thoughts?

EDIT1: I have discovered that Windows now has a comprehensive set of Application Recovery and Restart Functions. I have noticed over the past 2 years that Microsoft has become much better at restarting apps after say power outages. I suspect that it is due to this API's development. Fx, the RegisterApplicationRestart function solves my problem perfectly.

EDIT2: I had to give up trying to use Microsoft's Application and Recovery functions to save command line state. They were too restrictive and only worked for unhandled exceptions and non-responsiveness, and then they required interactive user screens. Fx, they wouldn't work if you had a power outage and just wanted your app to use internal cmdline state info to restart. Looks like I'll have to program my own.

rtischer8277
  • 496
  • 6
  • 27
  • I can't imagine this would work. In fact, I'm surprised you didn't get a "file in use" error when you tried. SUGGESTION: Familiarize yourself with the Win32 [shared memory APIs](https://learn.microsoft.com/en-us/windows/desktop/memory/creating-named-shared-memory), and see if that might give you what you're looking for. – paulsm4 Jan 07 '19 at 23:24
  • 2
    It'll work fine in a Posix environment, but in Windows - nope. Your use case is most probably misunderstood. Try describing it in more detail. – Ted Lyngmo Jan 07 '19 at 23:25
  • It doesn't work for upcoming c++20 std::filesystem either. – rtischer8277 Jan 14 '19 at 23:59

0 Answers0