Linux c : 遍歷並刪除指定目錄下的所有檔案
系統: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