系统:ubuntu17.10
遍历并删除指定目录下的所有文件
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int main()
{
char *dir_name = "/home/TmpFile/Test/"; //指定目录地址
DIR *dirp;
char strTmpPath[500] = "\0";
struct dirent *dp;
dirp = opendir(dir_name);
while((dp = readdir(dirp)) != NULL){
if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0){
continue;
}
// 以下注释部分可删除指定文件
/* if(strcmp(dp->d_name, "t.c") == 0) {
sprintf(strTmpPath, "%s/%s", dir_name, dp->d_name);
remove(strTmpPath);
printf("find t.c\n");
} */
printf("%s\n", dp->d_name);
sprintf(strTmpPath, "%s/%s", dir_name, dp->d_name);
int n = remove(strTmpPath);
printf("%d\n", n);
}
(void) closedir(dirp);
return 0;
}
"lsof.c" 44L, 702C 1,1 Top