C++ 删除文件夹和所有文件/子目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1149764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete folder and all files/subdirectories
提问by
How can I delete a folder with all it's files/subdirectories (recursive deletion) in C++?
如何在 C++ 中删除包含所有文件/子目录(递归删除)的文件夹?
回答by William Pursell
Seriously:
严重地:
system( "rm -rf /path/to/directory" )
Perhaps more what you're looking for, but unix specific:
也许您正在寻找更多,但特定于unix:
/* Implement system( "rm -rf" ) */
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/syslimits.h>
#include <ftw.h>
/* Call unlink or rmdir on the path, as appropriate. */
int
rm( const char *path, const struct stat *s, int flag, struct FTW *f )
{
int status;
int (*rm_func)( const char * );
switch( flag ) {
default: rm_func = unlink; break;
case FTW_DP: rm_func = rmdir;
}
if( status = rm_func( path ), status != 0 )
perror( path );
else
puts( path );
return status;
}
int
main( int argc, char **argv )
{
while( *++argv ) {
if( nftw( *argv, rm, OPEN_MAX, FTW_DEPTH )) {
perror( *argv );
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}
回答by avakar
You can use boost::remove_all
from Boost.Filesystem.
您可以boost::remove_all
从Boost.Filesystem使用。
回答by zeekvfu
You can use ftw()
, nftw()
, readdir()
, readdir_r()
to traverse a directory and delete files recursively.
But since neither ftw()
, nftw()
, readdir()
is thread-safe, I'll recommend readdir_r()
instead if your program runs in a multi-threaded environment.
您可以使用ftw()
, nftw()
, readdir()
,readdir_r()
遍历目录并递归删除文件。
但是,因为无论是ftw()
,nftw()
,readdir()
是线程安全的,我会建议readdir_r()
,而不是如果在一个多线程环境中的程序运行。
回答by zeekvfu
Standard C++ provides no means of doing this - you will have to use operating system specific code or a cross-platform library such as Boost.
标准 C++ 没有提供这样做的方法 - 您必须使用操作系统特定的代码或跨平台库,例如 Boost。