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 dùng C/C++


Xem mã mẫu C++ lấy danh sách file trong thư mục.

Thuật toán

Bắt đầu
    Khai báo con trỏ dr kiểu DIR
    Khai báo con trỏ en kiểu struct dirent
    Gọi opendir() mở tất cả file thư mục hiện tại
    Khởi tạo dr = opendir(".")
    Nếu(dr)
        while ((en = readdir(dr)) != NULL)
            in tên file dùng en->d_name
        gọi closedir() đóng thư mục
Kết thúc

Ví dụ

#include <iostream>
#include <dirent.h>
#include <sys/types.h>
using namespace std;

int main(void) {
    DIR *dr;
    struct dirent *en;
    dr = opendir("."); // mở thư mục hiện tại
    if (dr) {
        while ((en = readdir(dr)) != NULL) {
            cout << " \n" << en->d_name; // in tên thư mục/file
        }
        closedir(dr); // đóng thư mục
    }
    return 0;
}

Kết quả

BINSEARC.C BINTREE (1).C BINTREE.C BTREE.C BUBBLE.C c.txt file3.txt HEAP.C HEAPSORT.C HLINKLST.C INSERTIO.C LINKLIST.C LINKLST.C LLIST1.C players.cpp PolarRect.cpp QUEUE.C

Ví dụ (C)

#include <stdio.h>
#include <dirent.h>

int main(void) {
    DIR *dr;
    struct dirent *en;
    dr = opendir("."); // mở thư mục hiện tại
    if (dr) {
        while ((en = readdir(dr)) != NULL) {
            printf("%s\n", en->d_name); // in tên thư mục/file
        }
        closedir(dr); // đóng thư mục
    }
    return 0;
}

Kết quả

BINSEARC.C BINTREE (1).C BINTREE.C BTREE.C BUBBLE.C c.txt file3.txt HEAP.C HEAPSORT.C HLINKLST.C INSERTIO.C LINKLIST.C LINKLST.C LLIST1.C