在 CentOS 系统中,使用 readdir 函数可以读取目录中的文件和子目录。为了实现目录清理,你可以编写一个程序来遍历目录并删除不需要的文件。以下是一个简单的示例,使用 C 语言和 readdir 函数实现目录清理:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
void clean_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
char fullpath[1024];
if (!(dir = opendir(path))) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
clean_directory(fullpath);
} else {
if (remove(fullpath) == -1) {
perror("remove");
}
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
clean_directory(argv[1]);
return 0;
}
这个程序接受一个目录路径作为参数,然后递归地遍历该目录及其子目录。对于每个文件,它使用 remove 函数删除文件。请注意,这个程序会删除所有文件,因此在运行之前请确保你了解它的功能并已经备份了重要数据。
要编译此程序,请将其保存为 clean_directory.c,然后在终端中运行以下命令:
gcc clean_directory.c -o clean_directory
现在你可以使用 ./clean_directory 命令来清理指定目录。例如:
./clean_directory /path/to/your/directory
请谨慎使用此程序,以免意外删除重要文件。