Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Lấy danh sách file trong thư mục bằng C/C++

C++ chuẩn không cung cấp API liệt kê thư mục. Cách phổ biến:

Cách 1: Dùng lệnh hệ thống (system)

#include <iostream>
#include <cstdlib>
int main() {
    system("ls -l"); // Linux/macOS
    // system("dir"); // Windows
    return 0;
}

Nhược điểm: phụ thuộc OS, chậm, khó xử lý kết quả trong chương trình.

Cách 2: Dùng thư viện dirent.h (POSIX, Linux/macOS)

Cài đặt: #include <dirent.h>, #include <sys/types.h>.

#include <iostream>
#include <dirent.h>
#include <sys/types.h>

void list_dir(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) return;
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        std::cout << entry->d_name << std::endl;
    }
    closedir(dir);
}

int main() {
    list_dir("/home/username/Documents");
    return 0;
}

Cách 3: Windows API (FindFirstFile/FindNextFile)

Dùng windows.h, phức tạp hơn.

Cách 4: C++17 <filesystem> (Khuyến nghị hiện đại)

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    for (const auto &entry : fs::directory_iterator("/home/user/Documents")) {
        std::cout << entry.path().filename() << std::endl;
    }
    return 0;
}

Hỗ trợ cross-platform, OOP, lọc file, đệ quy thư mục con.