Deleting a file in c

How do I close the file and delete it?

I have the following code:

FILE *filePtr = fopen("fileName", "w");
...

      

Now I want to close filePtr and delete the file "fileName".

Should I:

fclose(filePtr);
remove("fileName");

      

Or:

remove("fileName");
fclose(filePtr);

      

Does it matter what I do first?

Thank!!

+3


source to share


4 answers


It depends on the OS. On * nix, deleting an open file leaves it open and data on disk, but removes the file name from the file system and actually deletes the file on close; some other operating systems may not allow you to delete an open file at all. Therefore, the former is recommended for maximum portability.



+3


source


You don't need a fopen

file for remove

it. But on Linux, if you remove

a fopen

ed a file, it will only be deleted after you close it. You can still read / write.



0


source


As the unlink (2) person says (for Unix systems):

The unlink () function removes the link named by the path from its directory and reduces the number of links to the file the link referred to. If that decrement reduces the link count of the file to zero, and no process on the file is open, then all resources associated with the file are reclaimed. If one or more processes open a file when the last link is deleted, the link is removed, but the file's deletion is delayed until all links to it have been closed.

So the order doesn't matter.

0


source


It makes sense for fclose

and then unlink .

-1


source







All Articles