在 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
文件。請注意,在執行批量操作時要小心,以免誤刪重要文件。在實際使用中,建議先在測試目錄中進行嘗試。