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!!
source to share
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.
source to share
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.
source to share