Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
Can a file move itself in C?

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda