Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda