linux文件夹文件操作

1.opendir

opendir是库函数,man 3 opendir可以获得详细信息,

opendir有两种形式:

            DIR *opendir(const char *name);

            DIR *fdopendir(int fd);

返回值:

           成功:返回指向文件夹流的指针。

           失败:返回NULL。

2.readdir

readdir也是库函数,man 3 readdir。

函数原型:

            struct dirent *readdir(DIR *dirp);

            int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

返回值:

             成功:返回 struct dirent 的指针,注意 readdir自己维护了 struct dirent 指针指向的空间。很可能是 static存储类的。

             失败或结束:返回NULL.

注意:

             使用readdir,每次将会返回文件夹内的一个文件目录,也就是文件夹内一个文件的信息,每次使用readdir,都将返回一个文件目录信息,readdir会自动指向下一个文件目录信息,知道结束,返回NULL。

           struct dirent {
               ino_t          d_ino;       /* inode number */
               off_t          d_off;       /* not an offset; see NOTES */
               unsigned short d_reclen;    /* length of this record */
               unsigned char  d_type;      /* type of file; not supported
                                              by all filesystem types */
               char           d_name[256]; /* filename */
           };

3.由于readdir是不可重入函数

由于readdir使用了static存储类,所以是不可重入的。

注:

        函数是否可重入判断依据是,是否使用了公共的资源,如果函数只是用了stack,由于函数自己的stack是不可能被其他函数使用到的,所以这种情况下函数是可重入的,如果函数使用了数据段,那么中断发生,公共的数据段的数据可能被其他函数修改,所以函数是不可重入的。

由于readdir是不可重入的,所以linux中提供了readdir第二中版本,也就是readdir_r,‘_r’表示是可重入函数。

猜你喜欢

转载自blog.csdn.net/blank2019/article/details/79535994
今日推荐