简体   繁体   English

删除 UNIX 下 C++ 中的文件

[英]Remove file in C++ under UNIX

How do you guys typically delete files on Linux OS?你们通常如何删除 Linux 操作系统上的文件? I am thinking of using the unlink function call, but I wonder if you have a better idea, as the C++ standard has no mention of file deletion operation and it is system dependent.我正在考虑使用unlink function 调用,但我想知道您是否有更好的主意,因为 C++ 标准没有提及文件删除操作,它取决于系统。

Yep -- the C++ standard leaves this stuff up to the OS, so if you're on Linux (or any POSIX system), unlink() is what you've got.是的——C++ 标准把这些东西留给了操作系统,所以如果你在 Linux(或任何 POSIX 系统)上, unlink()就是你所拥有的。

The C standard provides remove() , which you could try, but keep in mind that its behavior is unspecified for anything other than a 'regular file', so it doesn't really shield you from getting into platform-specific filesystem details (links, etc). C 标准提供了remove() ,您可以尝试,但请记住,除了“常规文件”之外,它的行为未指定,因此它并不能真正阻止您进入特定于平台的文件系统详细信息(链接, ETC)。

If you want something higher-level, more robust, and more portable, check out Boost Filesystem .如果您想要更高级别、更健壮和更便携的东西,请查看Boost Filesystem

The Standard includes a function called remove which does that.该标准包括一个名为remove的 function,它可以做到这一点。 Though i would prefer boost.filesystem for that (if i already use boost anyway).虽然我更喜欢boost.filesystem (如果我已经使用了 boost)。

#include <cstdio>

int main() {
    std::remove("/home/js/file.txt");
}

unlink() is defined by the POSIX standards, and hence will exist on any POSIX compatible system, and on quite a few that aren't POSIX compatible too. unlink()POSIX标准定义,因此将存在于任何与 POSIX 兼容的系统上,并且也存在于许多不兼容 POSIX 的系统上。

unlink is the correct way to do it.取消链接是正确的方法。

Note that recent kernels also offer unlinkat .请注意,最近的内核还提供unlinkat This function is faster than unlink if you have a file descriptor on the directory itself.如果目录本身有文件描述符,则此 function 比unlink更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM