纯c++删除自身目录,和该目录下的所有内容______以及创建文件夹

复制代码
头文件.h

#ifndef AUTODELETEADDFOLDER_H
#define AUTODELETEADDFOLDER_H #include <unistd.h> #include <stdlib.h> #include <errno.h> #include <dirent.h> #include <string.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> int CreateDir(const char *sPathName); void error_quit( const char *msg ); void change_path( const char *path ); void rm_dir( const char *path ); //格式 path = “/home/wc/qtproject/launchWidget/launchWidget/temp/” //说明 ZDnum :要创建多少个文件夹 void autoDelete_CreateFolder( std::string &path,const int ZDnum); #endif
复制代码

 

复制代码
源文件.cpp

#include "autodeleteaddfolder.h" int CreateDir(const char *sPathName) { char DirName[256]; strcpy(DirName, sPathName); int i,len = strlen(DirName); for(i=1; i<len; i++) { if(DirName[i]=='/') { DirName[i] = 0; if(access(DirName, NULL)!=0) { if(mkdir(DirName, 0755)==-1) { printf("mkdir error\n"); return -1; } } DirName[i] = '/'; } } return 0; } void error_quit( const char *msg ) { perror( msg ); exit( -1 ); } void change_path( const char *path ) { if ( chdir( path ) == -1 ) error_quit( "chdir" ); } void rm_dir( const char *path ) { DIR *dir; struct dirent *dirp; struct stat buf; char *p = getcwd( NULL, 0 ); if ( (dir = opendir( path ) ) == NULL ) error_quit( "OpenDir" ); change_path( path ); while ( dirp = readdir( dir ) ) { if ( (strcmp( dirp->d_name, "." ) == 0) || (strcmp( dirp->d_name, ".." ) == 0) ) continue; if ( stat( dirp->d_name, &buf ) == -1)//-1 error_quit( "stat" ); if ( S_ISDIR( buf.st_mode ) ) { rm_dir( dirp->d_name ); continue; } if ( remove( dirp->d_name ) == -1 ) //-1 error_quit( "remove" ); } closedir( dir ); change_path( p ); if ( rmdir( path ) == -1 ) //-1 error_quit( "rmdir" ); } void autoDelete_CreateFolder( std::string &path,const int ZDnum){ rm_dir(path.data()); CreateDir(path.data()); std::string pathYE = path; pathYE.append("YE/"); CreateDir(pathYE.data()); for(int i=0;i<ZDnum;i++) { std::string ZDfolder = path; ZDfolder.append("ZD").append(std::to_string(i)).append("/"); CreateDir(ZDfolder.data()); } }
复制代码

 

posted @   雾枫  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
历史上的今天:
2022-04-23 #pragma once 和 #ifndef 的区别、用法
2022-04-23 cls、清屏操作、在控制台窗口清屏
2022-04-23 exit(0)函数、退出应用程序
2022-04-23 知识点复习 (20)—— 职工管理系统
点击右上角即可分享
微信分享提示