I am trying to remove a file in my C
program. So I first of all check whether the file exists and then if it does I use the remove function. Here is my code:
if (!(f = fopen(position, "r")))
{
system("cls");
printf("User does not exist! Please enter the user again: ");
}
else
{
status = remove(position);
/*Check if file has been properly deleted*/
if(status == 0)
{
printf("User deleted successfully.\n\n");
break;
}
else
{
printf("Unable to delete the user\n");
}
}
Surely if the file definitely exists there should be no problem with removing the file. Anyway this bit of code is not working. And I just get returned "Unable to delete the user"
I have also tried using unlink along with importing unistd.h
but no luck.
What am I doing wrong?
Check this related question.
If you have to remove an fopen()
-ed path (file), it will be removed only if you fclose()
it.**
But I think if you just want to remove the file without using it just before, don't use fopen
and just call the remove
function.
**EDIT : It's not even known and it's system dependent.
So the best way for removing a file is to doing it is to call remove(path_of_file) when your not streaming it :
remove(path_of_file);
or if you need to open the file:
fopen/open;
(...)
fclose/fclose;
remove
From ISO/IEC9899
7.19.4.1 The remove function
[...]
Description
2 The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined.
Simply read the standard helps alot ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With