c - 删除功能是否保证删除文件?

标签 c c99 language-lawyer standard-library

关于 remove 函数的行为,C99 标准的措辞似乎有点模棱两可。

第 7.19.4.1 节第 2 段中:

The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew.

C99 标准是否保证remove 函数将删除 文件系统上的文件,或者实现可以简单地忽略 文件 - - 将文件保留在文件系统上,但当前程序无法通过该文件名访问 - 对于程序的其余部分?

最佳答案

我认为 C 标准不能保证任何事情,它说 (N1570, 7.21.4.1 2):

The remove function causes the file whose name is the string pointed to by filename to be no longer accessible by that name. A subsequent attempt to open that file using that name will fail, unless it is created anew. If the file is open, the behavior of the remove function is implementation-defined.

所以,如果你有一个病态的实现,我想它可以被解释为调用 remove() 仅仅具有使文件对该程序的这个正在运行的实例不可见的效果,但正如我所说,那将是病态的。

然而,并不是所有的人都是愚蠢的! remove() 的 POSIX 规范说,

If path does not name a directory, remove(path) shall be equivalent to unlink(path).

If path names a directory, remove(path) shall be equivalent to rmdir(path).

以及 unlink() 的 POSIX 文档很清楚:

The unlink() function shall remove a link to a file.

因此,除非您的实现 (a) 符合 POSIX 要求,并且 (b) 极其病态,否则您可以放心 remove() 函数将实际尝试删除文件,并且仅当文件实际删除时才返回 0

当然,在目前使用的大多数文件系统上,文件名与实际文件是分离的,因此如果您有五个指向一个 inode 的链接,该文件将一直存在,直到您删除所有这五个链接。

引用资料:

The Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
The Open Group Base Specifications Issue 7, IEEE Std 1003.1™, 2013 Edition
注意:“IEEE Std 1003.1 2004 Edition”是“IEEE Std 1003.1-2001 with corrigenda incorporated”。 “IEEE Std 1003.1 2013 Edition”是“IEEE Std 1003.1-2008 with corrigendum incorporated”。

关于c - 删除功能是否保证删除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108768/

相关文章:

linux - 如何使用make和编译为C99?

在 C 中将二叉树转换为数组(并稍后保存)

将 void 指针分配给非 void 指针的 C99 警告?

c - 如果fclose()失败,文件描述符是否仍然打开?

C99:我可以在 'for' 中的 block 开头声明变量吗?

c - 这个指针别名是如何工作的?

c++ - 函数定义中的四重 "const"

c++ - 聚合类型是否意味着它也是标准布局?

c - 如何在 uint64_t 中打印空格 (C)

c - 逐行填充数组(一维数组)