在 Linux 中,copendir() 函數用于打開一個目錄流,以便讀取目錄中的條目。要實現多線程遍歷目錄,你可以使用 POSIX 線程(pthreads)庫來創建多個線程,每個線程負責處理目錄的一部分。以下是一個簡單的示例,展示了如何使用 copendir() 和 pthreads 實現多線程遍歷目錄:
#<span>include <stdio.h></span> #<span>include <stdlib.h></span> #<span>include <dirent.h></span> #<span>include <pthread.h></span> #<span>include <string.h></span> typedef <span>struct {</span> char *path; DIR *dir; } thread_data_t; void *process_directory(<span>void *arg)</span> { thread_data_t *data = (thread_data_t *)arg; <span>struct dirent *entry;</span> 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: %sn", pthread_self(), full_path); // 如果需要遞歸遍歷子目錄,可以在這里調用 process_directory() 函數 } closedir(data->dir); pthread_exit(NULL); } int main(<span>int argc, char *argv[])</span> { 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() 函數本身。不過,在這種情況下,你需要確保正確地處理線程同步和資源管理,以避免潛在的競爭條件和資源泄漏。