readdir
是一個用于讀取目錄內容的函數,它在 POSIX 兼容的系統(如 Linux 和 macOS)上可用。要在不同平臺上實現跨平臺的目錄遍歷,你可以使用條件編譯來檢查系統類型,并根據需要調用適當的函數。
以下是一個簡單的示例,展示了如何使用 readdir
實現跨平臺目錄遍歷:
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
void list_directory_contents(const char *path) {
#if defined(_WIN32) || defined(_WIN64)
WIN32_FIND_DATA find_file_data;
HANDLE h_find = INVALID_HANDLE_VALUE;
char search_path[MAX_PATH];
snprintf(search_path, MAX_PATH, "%s\\*", path);
h_find = FindFirstFile(search_path, &find_file_data);
if (h_find == INVALID_HANDLE_VALUE) {
printf("Error: Could not open directory\n");
return;
}
do {
printf("%s\n", find_file_data.cFileName);
} while (FindNextFile(h_find, &find_file_data) != 0);
FindClose(h_find);
#else
DIR *dir = opendir(path);
struct dirent *entry;
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
#endif
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <directory_path>\n", argv[0]);
return 1;
}
list_directory_contents(argv[1]);
return 0;
}
在這個示例中,我們首先檢查是否在 Windows 平臺上(使用 _WIN32
或 _WIN64
宏)。如果是 Windows 平臺,我們使用 FindFirstFile
和 FindNextFile
函數來遍歷目錄。否則,我們在 POSIX 兼容的系統上使用 opendir
、readdir
和 closedir
函數。
要編譯此代碼,請根據您的平臺選擇適當的編譯器標志。例如,在 Linux 或 macOS 上,您可以使用以下命令:
gcc -o list_directory_contents list_directory_contents.c
在 Windows 上,您可以使用 MinGW 或 Visual Studio 編譯器。