Change file's name at runtime?

Jun 28, 2017 at 4:59am
How would I change the name of the file executed at runtime?
Pseudo code:
1
2
3
4
5
6
run
Do some things
change name from notrunning.exe to running.exe
do some more
change name from running.exe to notrunning.exe
exit

Now of course the above states is not how I would actually do this but is this possible? I know if I run a program and manually rename it (right click rename) I can do that but can the program do it to its self
Jun 28, 2017 at 6:42am
What you seem to want is a bit scary. Consider other approaches. For example, (Linux) services usually do put a temporary file in known folder to show that the service is running. It is easy to check whether the file exists. Firefox does that too.

However, your question. There are actually two:

A) Is it possible to rename a file?
Yes. C++17 will support it in OS-independent manner. http://en.cppreference.com/w/cpp/experimental/fs/rename

B) What is the filename of the binary?
That is more tricky. The first command-line argument to main() has a name, but if you have hard links, symlinks, aliases, etc then what is in the name?
Jun 28, 2017 at 8:01am
Before C++17 you might want to try std::rename. http://en.cppreference.com/w/cpp/io/c/rename

If the program is allowed to rename the executable file while running or not probably depends on the OS, any antivirus programs running, and the permission level of the process.

One thing I would be concerned about if you get it to work is what happens if the program crashes, or the power goes out while the program is running. That could easily lead to the file being named running.exe while the program is not running.
Jun 28, 2017 at 8:51am
The following worked on Windows (rather to my horror).

1
2
3
4
5
6
7
8
9
#include <cstdio>
#include <string>
using namespace std;

int main( int argc, char *argv[] )
{
   string filename = argv[0];   if ( filename.find( ".exe" ) == string::npos ) filename += ".exe";
   rename( filename.c_str(), "scary.exe" );
}


Note that this changes the name of the file in the filesystem, not what's in memory. (At least, that's what I thought until I put a pause line in and looked in TaskManager whilst it was running. Scary indeed!)
Last edited on Jun 28, 2017 at 8:57am
Topic archived. No new replies allowed.