Writing in the executable while running the program

I'm writing a C program and I would like to be able to store data inside the executable file. I tried making a function to write a single byte at the end of the file but it looks like it can't open the file because it reaches the printf and then gives "segmentation fault".

void writeByte(char c){

    FILE *f;
    f = fopen("game","wb");

    if(f == 0)
        printf("\nFile not found\n");

    fseek(f,-1,SEEK_END);
    fwrite(&c,1,sizeof(char),f);

    fclose(f);

}

The file is in the correct directory and the name is correct. When I try to read the last byte instead of writing it works without problems.

Edit: I know I should abort the program instead of trying to write anyway but my main problem is that the program can't open the file despite being in the same directory.

1 answer

  • answered 2022-01-25 14:23 Jakob Stark

    There are several unrelated problems in your code and the problem you're trying to solve.

    First you lack proper error handling. If any function that can fail (like e.g. fopen) fails, you should act accordingly. If, for example you did

    #include <error.h>
    #include <errno.h>
    ...
    f = fopen("game","wb");
    if ( f == NULL ) {
        error(1,errno,"File could not be opened");
    }
    ...
    

    You would have recieved an useful error message like

    ./game: File could not be opened: Text file busy
    

    You printed a message, which is not even correct (the file not beeing able to be opened is somthing different, than not beeing found) and continued the program which resulted in a segmentation fault because you dereferenced the NULL pointer stored in f after the failure of fopen.

    Second As the message tells us (at least on my linux machine), the file is busy. That means, that my operating system does not allow me to open the executable I'm running in write mode. The answers to this question lists numerous source of the explanation of this error message. There might be ways to get around this and open a running executable in write mode, but I doubt this is easy and I doubt that this would solve your problem because:...

    Third Executable files are stored in a special binary format (usually ELF on Linux). They are not designed to be manually modified. I don't know what happens if you just append data to it, but you could run into serious problems if your not very careful and know what you're doing.

    If you just try to store data, use another plain and fresh file. If you're hoping to append code to an executable, you really should gather some background information about ELF files (e.g. from man elf) before continuing.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum