在 Ubuntu 下,要使用 copendir
函數,首先需要包含相應的頭文件,并鏈接到正確的庫。copendir
函數用于打開一個目錄流,通常與 readdir
和 closedir
函數一起使用來遍歷目錄中的文件和子目錄。
以下是一個簡單的示例,展示了如何在 Ubuntu 下使用 copendir
函數:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打開目錄
dir = opendir("/path/to/directory");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 遍歷目錄中的文件和子目錄
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// 關閉目錄
closedir(dir);
return EXIT_SUCCESS;
}
將上述代碼保存為 list_directory.c
,然后在終端中使用以下命令編譯:
gcc list_directory.c -o list_directory
最后,運行生成的可執行文件:
./list_directory
這將列出指定目錄中的所有文件和子目錄。請確保將 /path/to/directory
替換為您要列出的實際目錄路徑。