Is it possible to save a variable internally and read/write to it after program shuts down?

447 views Asked by At

I've been looking for some time now without some hope. Basically I was wondering if it's possible to save a variable and read from it inside the executable after the program exits.

I know that one can use the fstream function to store the variable in a external file, But I'm looking for a way to store it internaly like in the .exe.

string l;
cin >> l;
// function to save it internally.....

Thanks in advance o.o

2

There are 2 answers

0
spectras On BEST ANSWER

Here are a few hints on why it's not a good idea.

  • It is no better than using another file.
    • You cannot access a big block of memory as “all my data” and write it into a file, so you will have to serialize / unserialize properly. Once you have that code available, it is actually more work messing with a complex file format (be it ELF or PE) than writing to an empty file.
  • It is worse actually.
    • Bugs in writing the data could make your program unworkable.
    • Multiple users cannot each have their own data.
  • Your executable file is normally not writable.
    • On Unix-based systems, binary files are typically installed to system directories and a normal user simply cannot change them.
    • Even if running as root, it's not uncommon for system partition to be read-only (my own setup has / mounted as read-only for instance).
    • On Windows systems, although it is more common to run with admin rights, it's not universal and, anyway, the binary file of an running program is locked.
  • Even if you manage to workaround all this, it prevents data portability.
    • Install and update of your program and data is gone.
    • There is no way to backup your data and restore it later (possibly on another system).
  • The only programs modifying executables those days are malware. For this reason, intercepting executable-modifying programs and shutting them down is one of the most basic features of anti-malware software.
    • Along those lines, on system that implement signed binary or any kind of trust system, your modified binary won't pass signature tests.

So, lots of quirks, lots of complex workarounds both in your program and in user experience (need to request special permissions, tricky save and backup, very probable data loss). While on the other hand a simple save to a data file is easy to implement and user-friendly.

2
Alpha Mineron On

As mentioned by @drescherjm and @Peter in the comments, such a practice is what the security software look for, so its not really the brightest of idea. I'm not well aware of your intentions but if you are trying to implement co-routines within your programs here's what you can do:

  • Create a static variable, say static int state=0;, and use that to implement co-routines on the scale of a program-lifetime.
  • Use a file, say "Sys_Status.dat" to store those variables' info.