Chương trình C liệt kê tất cả file và thư mục con trong một thư mục (mặc định thư mục hiện tại).
Phương pháp
- Dùng
<dirent.h>: DIR*, struct dirent opendir(".")mở thư mục hiện tạireaddir()đọc lần lượt entryclosedir()đóng thư mục
Chương trình mẫu
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *entry;
DIR *dir = opendir(".");
if (!dir) {
printf("Không thể mở thư mục!\n");
return 1;
}
while ((entry = readdir(dir)) != NULL)
printf("%s\n", entry->d_name);
closedir(dir);
return 0;
}
Kết quả mẫu
. .. cprograms prog1.c prog2.c prog3.c ... prog41.c
Giải thích: "." là thư mục hiện tại, ".." là thư mục cha. Các file .c và thư mục con được liệt kê.
Mở rộng: Kiểm tra entry->d_type để phân biệt file/thư mục (DT_REG, DT_DIR).