在 Linux 中,copendir() 函數用于打開一個目錄流,以便讀取目錄中的條目。要實現多線程遍歷目錄,你可以使用 POSIX 線程(pthreads)庫來創建多個線程,每個線程負責處理目錄的一部分。以下是一個簡單的示例,展示了如何使用 copendir() 和 pthreads 實現多線程遍歷目錄:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <pthread.h>
#include <string.h>
typedef struct {
char *path;
DIR *dir;
} thread_data_t;
void *process_directory(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
struct dirent *entry;
char full_path[1024];
while ((entry = readdir(data->dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(full_path, sizeof(full_path), "%s/%s", data->path, entry->d_name);
printf("Thread %ld: %s\n", pthread_self(), full_path);
// 如果需要遞歸遍歷子目錄,可以在這里調用 process_directory() 函數
}
closedir(data->dir);
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
char path[1024];
snprintf(path, sizeof(path), "%s", argv[1]);
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return 1;
}
pthread_t threads[4];
thread_data_t thread_data[4];
for (int i = 0; i < 4; ++i) {
thread_data[i].path = path;
thread_data[i].dir = dir;
if (pthread_create(&threads[i], NULL, process_directory, (void *)&thread_data[i]) != 0) {
perror("pthread_create");
return 1;
}
}
for (int i = 0; i < 4; ++i) {
pthread_join(threads[i], NULL);
}
closedir(dir);
return 0;
}
這個示例程序接受一個目錄路徑作為命令行參數,然后創建 4 個線程來遍歷該目錄。每個線程都會調用 process_directory() 函數來處理目錄的一部分。在這個示例中,我們只是簡單地打印出每個文件的完整路徑,但你可以根據需要修改這個函數來實現你的需求。
請注意,這個示例程序沒有處理遞歸遍歷子目錄的情況。如果你需要遞歸遍歷子目錄,可以在 process_directory() 函數中調用 process_directory() 函數本身。不過,在這種情況下,你需要確保正確地處理線程同步和資源管理,以避免潛在的競爭條件和資源泄漏。