如何在C程序中删除文件?
如何关闭文件并将其删除?
我有以下代码:
FILE *filePtr = fopen("fileName", "w");
...
现在我想关闭 filePtr 并删除文件“fileName”。
我应该:
fclose(filePtr);
remove("fileName");
或者:
remove("fileName");
fclose(filePtr);
我先做什么重要吗?
谢谢!!
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!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于操作系统。在 *nix 上,删除打开的文件会使其保持打开状态并保留磁盘上的数据,但会从文件系统中删除文件名,并在关闭时实际删除该文件;某些其他操作系统可能根本不允许您删除打开的文件。因此,建议使用前者以获得最大的便携性。
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.
fclose
然后unlink 更有意义。It makes more sense to
fclose
and then unlink.正如 man unlink(2) 所说(对于 Unix 系统):
所以顺序根本不重要。
As man unlink(2) says (for Unix systems) :
So the order doesn't matter at all.
您不需要
fopen
文件来删除
它。但是,在 Linux 中,如果您删除
一个fopen
ed文件,只有在关闭它之后它才会被删除。您仍然可以读取/写入它。You do not need to
fopen
a file toremove
it. But, in linux, if youremove
anfopen
ed file, it will be deleted only after closing it. You can still read/write to it.