Removal of files in c

Asked

Viewed 32 times

0

I am doing a job and arrived at a part of removing file that the user wants, but it reads and does not remove. to remove I should use extension (.txt)? if yes, how?

void removeCliente() {
    char codigo [50]; int excl;
    int *p;
    char * file_name;
    //FILE* verifica;
    printf("entre com o código do cliente que deseja excluir:");
    scanf("%s",&codigo);
    file_name=codigo;

      FILE *fo = fopen(file_name,"r");
    if (fo == NULL){
        printf("Ocorreu um erro!");
        //return 0;
    }

    else{
            fclose(file_name);
    fflush(stdin);
       remove(file_name);
    printf("usuario %d removido com sucesso");
    //sleep(10);
    }
    menugerente();
}
  • The file name should be exactly the same as the one that exists. If you have an extension, you should put it. And if it’s in another directory, it should have the complete path.

  • is in the same directory. but how do I put the file extension? if the input name does not have

  • Did my answer solve your problem? If yes, mark it as answered. If not, tell us what is still in doubt. If you don’t know how to mark as a response, take a look at https://answall.com/tour

1 answer

0

As previously commented, it seems that its entry does not have the file extension and its file has.

You can use a sprintf to generate the new file name.

So, you can do it this way:

void removeCliente() {
    char codigo[50];
    char file_name[32];

    printf("Entre com o código do cliente que deseja excluir:");

    scanf("%s", &codigo);

    // Setamos a variável file_name como sendo o texto de codigo mais a adição do texto "txt"
    sprintf(file_name, "%s.txt", codigo);

    FILE *fo = fopen(file_name, "r");
    if (fo == NULL) 
        printf("Ocorreu um erro! O usuario não existe");
    else 
    {
        fclose(fo);
        fflush(stdin);
        remove(file_name);
        // Você havia colocado um %d sendo que era uma string, então, alterei para %s
        printf("usuario %s removido com sucesso", codigo);
    }

    menugerente();
}

I also point out that if you are in another folder, you should put the full path to remove correctly.

So, your sprintf could have one more argument being the default path, set somewhere in your project.

Example:

sprintf(file_name, "%s\\%s.txt", caminho_do_arquivo, codigo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.