dirent.h使用详解

dirent.h使用详解

LINUX下历遍目录的方法一般是这样的
打开目录-》读取-》关闭目录
相关函数是
opendir -> readdir -> closedir

#include <dirent.h>
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

好了,三个函数都出来了,原型就是上面。

opendir用于打开目录,是类似于流的那种方式,返回一个指向DIR结构体的指针,参数*dirname是一个字符数组或者字符串常量;

readdir函数用于读取目录,只有一个参数,就是opendir返回的结构体指针,或者叫句柄更容易理解些吧。这个函数也返回一个结构体指针 dirent *;

C++ <dirent.h>目录操作函数

包含头文件

#include <dirent.h>

struct dirent结构

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字符 */
}

DIR结构

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;

DIR和dirent的指针都可以打开dir,dirent 还可以获取文件名。

opendir(打开目录)

readdir(读取目录)

closedir(关闭目录)

https://blog.csdn.net/pj_wxyjxy/article/details/129985880

https://blog.csdn.net/dream_allday/article/details/75243818

posted @ 2025-04-22 15:03  michaelchengjl  阅读(229)  评论(0)    收藏  举报