【C++ 系統控制 #1】C++ 利用 dirent.h 計算資料夾的檔案數量 count files sample code (內含範例程式碼)

我們可以使用 dirent.h 這個 library 幫助我們偵測特定資料夾底下的檔案數量,
下方的程式碼只需要修改 path ,更換為自己想要偵測的路徑即可。

Sample Code (範例程式碼)

#include <dirent.h>

int file_count = 0;
DIR * dirp;
struct dirent * entry;

path = "/home/ubuntu/Desktop/"

dirp = opendir(path); /* There should be error handling after this */
while ((entry = readdir(dirp)) != NULL) {
    if (entry->d_type == DT_REG) { /* If the entry is a regular file */
         file_count++;
    }
}
closedir(dirp);

Reference

Counting the number of files in a directory using C