當前位置:才華齋>計算機>C語言>

C/C++如何獲取目錄下的檔案列表資訊

C語言 閱讀(1.22W)

C/C++如何獲取目錄下的檔案列表資訊?下面下面就一起來了解看看具體的方法吧!

C/C++如何獲取目錄下的檔案列表資訊

  1.資料結構

複製程式碼 程式碼如下:

struct dirent

{

long d_ino; /* inode number 索引節點號 */

off_t d_off; /* offset to this dirent 在目錄檔案中的偏移 */

unsigned short d_reclen; /* length of this d_name 檔名長 */

unsigned char d_type; /* the type of d_name 檔案型別 */

char d_name [NAME_MAX+1]; /* file name (null-terminated) 檔名,最長255字元 */

}

struct __dirstream

{

void *__fd; /* `struct hurd_fd' pointer for descriptor. */

char *__data; /* Directory block. */

int __entry_data; /* Entry number `__data' corresponds to. */

char *__ptr; /* Current pointer into the block. */

int __entry_ptr; /* Entry number `__ptr' corresponds to. */

size_t __allocation; /* Space allocated for the block. */

size_t __size; /* Total valid data in the block. */

__libc_lock_define (, __lock) /* Mutex lock for this structure. */

};

typedef struct __dirstream DIR;

 2.程式示例

其中程式中win不支援檔案型別(d_type),可以根據檔名稱字尾來判斷檔案型別;linux可以直接使用d_type判斷是目錄還是檔案。

複製程式碼 程式碼如下:

#include

#include

#include

#include

int main(){

DIR *dir;

struct dirent *ptr;

dir = opendir("."); ///open the dir

while((ptr = readdir(dir)) != NULL) ///read the list of this dir

{

#ifdef _WIN32

printf("d_name: %sn", ptr->d_name);

#endif

#ifdef __linux

printf("d_type:%d d_name: %sn", ptr->d_type,ptr->d_name);

#endif

}

closedir(dir);

return 0;

}

程式輸出: