入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

readdir(系统调用)

创建时间:2015-07-13 投稿人: 浏览次数:720

glib中没有提供readdir系统调用,而是封装了readdir系统调用。

系统调用

//使用系统调用读出的数据是以下的结构
struct old_linux_dirent {
    long  d_ino;/* inode number */
    off_t d_off;/* offset to this old_linux_dirent */
    unsigned short d_reclen;/* length of this d_name */
    char  d_name[NAME_MAX+1]; /* filename (null-terminated) */

}

//关于参数 --- fd 文件分配符  dirp 目录数据  count参数没有用处,可为任意值。 
//关于返回值 --- 返回 -1 表示出错 0 表示没有目录数据 1 便是读取成功
int readdir(int fd, struct old_linux_dirent *dirp,unsigned int count);


封装函数

struct dirent *readdir(DIR *dirp);

linux下man 2 readdir有如下的描述

DESCRIPTION
       This is not the function you are interested in.  Look at readdir(3) for
       the POSIX conforming C library interface.  This page documents the bare
       kernel system call interface, which is superseded by getdents(2).
       这是不是你所感兴趣的函数.看看符合POSIX的C库的接口的readdir(3)。该文档写了的是内核的系统调用,
       该系统调用已被getdents(2)取代。

       readdir()  reads  one  old_linux_dirent  structure  from  the directory
       referred to by the file descriptor fd into the  buffer  pointed  to  by
       dirp.   The  argument  count  is  ignored; at most one old_linux_dirent
       structure is read.
       readdir()从目录中读取一个old_linux_dirent结构,从文件描述符fd指向的文件读取到指向dirp缓冲区。
       参数count被忽略;至多一个old_linux_dirent结构被读取。

       The old_linux_dirent structure is declared as follows:

           struct old_linux_dirent {
               long  d_ino;              /* inode number */
               off_t d_off;              /* offset to this old_linux_dirent */
               unsigned short d_reclen;  /* length of this d_name */
               char  d_name[NAME_MAX+1]; /* filename (null-terminated) */
           }

       d_ino is an inode number.  d_off is the distance from the start of  the
       directory  to  this  old_linux_dirent.  d_reclen is the size of d_name,
       not counting the terminating null byte ("").  d_name is a null-termi‐
       nated filename.


RETURN VALUE
       On  success,  1  is  returned.  On end of directory, 0 is returned.  On
       error, -1 is returned, and errno is set appropriately.
       成功则返回1。 到达目录结尾则返回0.出错,返回-1,errno被设置。

如果要使用该系统调用,可以自己调用。

#include <stdio.h>
#include <fcntl.h>
#include <linux/types.h>
#include <linux/dirent.h>
#include <linux/unistd.h>

int errno;

_syscall3(int,readdir,int,fd,struct old_linux_dirent *,dirp,uint,count);

int main(int argc,char **argv,char **envp)
{

    int fd=0;
    struct old_linux_dirent dir;

    fd=open(argv[1],O_RDONLY,0);
    if(fd==-1)
    {
        printf("fd == -1 
");
        exit(1);
    }

    while(1)
    {
        int ret=readdir(fd,&dir,1);
        if(ret==-1)
        {
            printf("ret == -1");
            exit(1);
        }


        if(ret==0)
            break;

        printf("%s 
"dir.d_name);
    }

    return 0;
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。