How to remove a file in C program?

loopi picture loopi · Apr 24, 2011 · Viewed 10.6k times · Source

How do I close a file and remove it?

I have the following code:

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

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

Should I:

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

Or:

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

Does it matter which I do first?

Thanks!!

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Apr 24, 2011

That is OS-dependent. On *nix, deleting an open file leaves it open and the data on disk, but removes the filename from the filesystem, and actually deletes the file on close; some other operating systems may not let you delete an open file at all. Therefore the former is recommended for maximum portability.