Remove function not working

I am trying to delete a file in my program C

. So I first check if the file exists and then if 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");
        }
    }

      

Of course, if the file definitely exists, there should be no problem deleting the file. This bit of code doesn't work anyway. And I'll just come back"Unable to delete the user"

I've also tried using unlink along with imports unistd.h

, but no luck.

What am I doing wrong?

+3


source to share


3 answers


Check out this related question .

If you need to remove the fopen()

-ed (file) path , it will only be removed if you do fclose()

. **

But I think if you just want to delete the file without using it immediately before then don't use fopen

and just call the function remove

.

** EDIT: It's not even known and is system dependent.



Thus, the best way to delete a file is to perform delete (path_of_file) when you are not streaming it:

remove(path_of_file);

      

or if you need to open the file:

fopen/open;
(...)
fclose/fclose;
remove

      

+4


source


From ISO / IEC9899

7.19.4.1 Delete function

[...]



Description

2 The delete function calls the file whose name is the string pointed to by the file name to be inaccessible by that name. A subsequent attempt to open this file using this name will fail unless it is recreated. If the file is open, the behavior of the delete function is implementation-defined .

Just read that the standard helps alot;)

+1


source


You can use this piece of code to delete the file. What is the first check of the file exists or not, then try to delete the file.

if( access( fname, F_OK ) != -1 ) {
   status = remove(position);
        /*Check if file has been properly deleted*/
        if(status == 0){
            printf("User deleted successfully.\n\n");
        }
        else{
            printf("Unable to delete the user\n");
        }

} else {
    // file doesn't exist
 printf("Sorry! file doesn't exist\n");
}

      

0


source







All Articles