Linux下,用递归的方法实现了删除一个目录下的所有文件。有需要的可以参考:
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
using namespace std;
//LINUX下历遍目录 opendir -> readdir -> closedir
// 打开 -> 读取 -> 关闭
void Getfilepath(const char *path, const char *filename, char *filepath)
{
strcpy(filepath, path);
if(filepath[strlen(path) - 1] != '/')
strcat(filepath, "/");
strcat(filepath, filename);
printf("path is = %s\n",filepath);
}
bool DeleteFile(const char* path)
{
DIR *dir;
struct dirent *dirinfo;
struct stat statbuf;
char filepath[256] = {0};
lstat(path, &statbuf);
if (S_ISREG(statbuf.st_mode))//判断是否是常规文件
{
remove(path);
}
else if (S_ISDIR(statbuf.st_mode))//判断是否是目录
{
if ((dir = opendir(path)) == NULL)
return 1;
while ((dirinfo = readdir(dir)) != NULL)
{
Getfilepath(path, dirinfo->d_name, filepath);
if (strcmp(dirinfo->d_name, ".") == 0 || strcmp(dirinfo->d_name, "..") == 0)//判断是否是特殊目录
continue;
DeleteFile(filepath);
rmdir(filepath);
}
closedir(dir);
}
return 0;
}
int main(int argc, char *argv[])
{
char* path = "文件夹路径";
DeleteFile(path);
return 0;
}
转自:https://blog.youkuaiyun.com/liuhanwen_1993/article/details/83657844