在 Debian 系统中,readdir
是一个用于读取目录内容的函数,通常在 C 语言编程中使用
sudo apt-get update
sudo apt-get install build-essential
readdir_example.c
的 C 语言源文件,并添加以下代码:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
这段代码会读取指定目录下的所有文件和子目录,并将它们的名称打印到控制台。
gcc
编译源文件:gcc readdir_example.c -o readdir_example
./readdir_example /path/to/directory
这将输出指定目录下的所有文件和子目录。
如果你想要对目录中的文件执行批量操作,可以在 while
循环中添加相应的代码。例如,如果你想要删除目录中的所有 .txt
文件,可以使用以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
char *path = argv[1];
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (strstr(entry->d_name, ".txt")) {
char file_path[1024];
snprintf(file_path, sizeof(file_path), "%s/%s", path, entry->d_name);
if (remove(file_path) != 0) {
perror("remove");
} else {
printf("Deleted: %s\n", file_path);
}
}
}
closedir(dir);
return 0;
}
这段代码会删除指定目录下的所有 .txt
文件。请注意,在执行批量操作时要小心,以免误删重要文件。在实际使用中,建议先在测试目录中进行尝试。