1. 程式人生 > 其它 >[Linux] C 語言遍歷資料夾

[Linux] C 語言遍歷資料夾

[Linux] C 語言遍歷資料夾

hanjialeOK

於 2021-04-04 21:13:16 釋出

439
收藏 1
分類專欄: C/C++
版權

C/C++
專欄收錄該內容
31 篇文章0 訂閱
訂閱專欄
包含標頭檔案

#include <dirent.h>
1
opendir 用於開啟資料夾,readdir 用於獲取資料夾中每個檔案並用結構體 dirent 儲存。

關於檔案型別 d_type,常用型別如下

0 # 未知
4 # 目錄
8 # 檔案
10 # 連結
1
2
3
4
用法如下:

int main(int argc, char* argv[])
{
DIR *dir = NULL;
struct dirent *file;
if((dir = opendir("../images/")) == NULL) {
printf("opendir failed!");
return -1;
}
while(file = readdir(dir)) {
// 判斷是否為檔案
if (file->d_type != 8) continue;
cout << file->d_name << endl;
// 為檔案加上相對路徑
char fileName[20] = "../images/";
strcat(fileName, file->d_name);
}
closedir(dir);
return 1;
}
————————————————
版權宣告:本文為CSDN博主「hanjialeOK」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/weixin_43742643/article/details/115433272