How to delete a file (not txt) in C?

Asked

Viewed 55 times

0

I’m creating a program that puts each student’s grades in a different file. The user places the student’s code and this code becomes the name of a file that is not txt (I don’t know how to make it txt). However I am not able to delete this file. For example, the user will enter the student’s code and I want the file with that code to be deleted. I tried to use the remove() function, but it only works for the txt file. I also tried to use the unlink() function but did not understand mt well how it works.

Since now, obg!!

void apagar()
{

    char nusp[8];

    printf("--------- CONSULTA ---------\n\n");

    printf("Digite o NUSP do aluno(a): ");

    gets(nusp);
    FILE *consultar;
    consultar = fopen(nusp,"r");
    if (consultar==NULL)
    {
        printf("\nAluno ainda nao cadastrado.");
    }
    else
    {
        printf("\n");
        remove(nusp);
        printf("\nAluno removido com sucesso!\n\n");
        system("pause");
    }
}
  • You can show the code you’ve already written?

  • 3

    "I tried to use the remove() function, but it only works for txt file." - This is doubtful to say the least. The function remove() does not even want to know if the file is txt or not, it removes any file. You probably did something stupid in the code trying to use it, so it would be nice to see your code.

  • edited the post and put the code

  • @Victorstafusa depends on whether it is file . dat or . bin then the commands change

  • 1

    @YODA Look at the two examples here. In the second example, it is a binary file (the program itself).

  • @Victorstafusa understood... thank you!

Show 1 more comment

1 answer

1


You cannot delete a file that is open. Close the file with fclose(consultar); before trying to delete it.

And please don’t use gets never. Reasons not to use gets I’ll explain in this answer and also talk about it in this other. Use fgets(nusp, 8, stdin); instead of gets(nusp);.

  • It worked, very obg. I think I had heard about n using the gets, but I didn’t remember pq, now only fgets, vlw hahaha

Browser other questions tagged

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