Can a file move itself in C?

Viewed 69

I'm trying to make a file install itself into the system (linux).

Every method I use (rename, system(mv), execl, etc) fails. Is there anyway to make a running executable move itself while running? The closest I've come is renaming it but only within the same directory.

1 Answers

The code below "copies" itself to a new destination and gets deleted after termination. Basically, the code makes a new entry (hardlink) at the specified location and removes the current one (from the calling directory). The contents of the file will be preserved, since there is no copy and deletion involved.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libgen.h>

int main(int argc, const char *argv[])
{   
    //current filepath (dir + name)
    const char* file_path = argv[0];

    //extract filename component (needed to append to newdir)
    char* file_name_ = strdup(file_path);
    char* file_name = basename(file_name_);

    //make new path name
    char* new_dir = "<put your destination here - with no slash ('/') at the end>";
    size_t new_path_len = strlen(new_dir) + strlen(file_name) + 2; //two extra bytes: '/' + '\0'
    char new_path[new_path_len];
    snprintf(new_path, new_path_len, "%s/%s", new_dir, file_name);

    //make a new name for a file (hardlink)
    link(file_path, new_path);
    //delete a name and possibly the file it refers to
    unlink(file_path);

    //cleanup
    free(file_name_);

    return 0;
}

Hint: careful study of the documenation to link is highly recommended (especially the ERRORS section).

References:

basename - parse pathname components
link - make a new name for a file
unlink - delete a name and possibly the file it refers to

Related