PDA

View Full Version : Getting an executable to write to itself


ghell
12-01-2007, 06:56 PM
Is it possible to get an executable to write to itself? The application I am writing needs to check for updates and if there are any, update itself.

Here is an example of what I want to do:#include <stdio.h>

int main(int argc, char* argv[])
{
/* Open self for writing */
FILE* f = fopen(argv[0], "w");
if(f == NULL)
{
fprintf(stderr, "Unable to open file %s.", argv[0]);
return 1;
}

fclose(f);
return 0;
}
I actually want to do it from C# on Windows but it was easier to demonstrate the problem in C.

What I am currently doing is downloading to a temporary file, getting the program to run another executable and quit. The other executable then moves the temporary file over the first executable while it is not in use. However, this isn't very elegant and I have seen updater software before that did not exhibit this behaviour.

Dunna
12-04-2007, 12:52 AM
You cannot write to a program that is executing. Thus, a running program cannot 'update' itself. However, you could have your exe spawn an updater exe. Then your program terminates, the updater updates, and then the updater restarts your program. That's about it.

oracleguy
12-04-2007, 09:00 AM
You cannot write to a program that is executing. Thus, a running program cannot 'update' itself.

That doesn't apply on Unix based operating systems usually. You can replace a running executable file because it loads the whole file into memory when it starts. But I have the feeling gshell, you are wanting to do this on Windows. In which case, Dunna is correct.