删除文件夹和所有文件/子目录 [英] Delete folder and all files/subdirectories

查看:375
本文介绍了删除文件夹和所有文件/子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中删除包含所有文件/子目录(递归删除)的文件夹?

解决方案

/ p>

  system(rm -rf / path / to / directory)
pre>

也许更多的是你正在寻找,但unix特定:

  / *实现系统(rm -rf)* / 

#include< stdlib.h>
#include< unistd.h>
#include< stdio.h>
#include< sys / syslimits.h>
#include< ftw.h>


/ *根据需要在路径上调用unlink或rmdir。 * /
int
rm(const char * path,const struct stat * s,int flag,struct FTW * f)
{
int status;
int(* rm_func)(const char *);

switch(flag){
默认值:rm_func = unlink;打破;
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;
}


How can I delete a folder with all it's files/subdirectories (recursive deletion) in C++?

解决方案

Seriously:

system( "rm -rf /path/to/directory" )

Perhaps more what you're looking for, but unix specific:

/* 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;
}

这篇关于删除文件夹和所有文件/子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆