removing a file in c

我的梦境 提交于 2019-12-18 09:03:08

问题


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!!


回答1:


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.




回答2:


As man unlink(2) says (for Unix systems) :

The unlink() function removes the link named by path from its directory and decrements the link count of the file which was referenced by the link. If that decrement reduces the link count of the file to zero, and no process has the file open, then all resources associated with the file are reclaimed. If one or more process have the file open when the last link is removed, the link is removed, but the removal of the file is delayed until all references to it have been closed.

So the order doesn't matter at all.




回答3:


You do not need to fopen a file to remove it. But, in linux, if you remove an fopened file, it will be deleted only after closing it. You can still read/write to it.




回答4:


It makes more sense to fclose and then unlink.



来源:https://stackoverflow.com/questions/5769785/removing-a-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!