Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

วิธีดูรายการไฟล์ในไดเรกทอรีด้วย C/C++

C++ มาตรฐานไม่มีฟังก์ชันสำหรับนี้โดยตรง สามารถใช้คำสั่งระบบ (system command) เรียก ls แทน

ตัวอย่างใช้ system()

#include <iostream>
int main() {
    char command[50] = "ls -l";
    system(command);
    return 0;
}

ผลลัพธ์ตัวอย่าง

-rwxrwxrwx 1 root root  9728 Feb 25 20:51 a.out
-rwxrwxrwx 1 root root   131 Feb 25 20:44 hello.cpp
...

บน Windows ใช้ dir แทน ls

วิธีที่ยืดหยุ่นกว่า: ใช้ไลบรารี dirent

ติดตั้งจาก github.com/tronkko/dirent

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

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

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

ผลลัพธ์

a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py