5

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?

maxisme
  • 3,974
  • 9
  • 47
  • 97

3 Answers3

7

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
Community
  • 1
  • 1
Charlon
  • 363
  • 2
  • 16
  • 1
    "it will be removed only if you fclose() it." is incorrect. It is assumable, but we can't know, as we don't know what compiler he used and what system he is on. As you can see in my answer, without that information we can't know it will only be removed if its `fclose()`ed or what ever else, as it is implementation defined. – dhein Dec 03 '14 at 12:32
2

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 ;)

Community
  • 1
  • 1
dhein
  • 6,431
  • 4
  • 42
  • 74
0

You can use this code snippet to delete a file . Which first check for file exist or not then try to delete a 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");
}
sonus21
  • 5,178
  • 2
  • 23
  • 48