您的位置:首页 > 其它

readdir(系统调用)

2015-07-13 20:13 211 查看
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 ('\0').  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 \n");
exit(1);
}

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

if(ret==0)
break;

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

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: