![](/img/trans.png)
[英]Why was a readdir function added to POSIX library interface when there is a readdir kernel function?
[英]Is it possible to implement readdir() in Ubuntu 12.10 (kernel 3.5)?
在K & R
8.6中,作者实现了readdir()
的简单版本。 代码如下:
#include <sys/dir.h> /* local directory structure */
/* readdir: read directory entries in sequence */
Dirent *readdir(DIR *dp)
{
struct direct dirbuf; /* local directory structure */
static Dirent d; /* return: portable structure */
while (read(dp->fd, (char *) &dirbuf, sizeof(dirbuf))
== sizeof(dirbuf)) {
if (dirbuf.d_ino == 0) /* slot not in use */
continue;
d.ino = dirbuf.d_ino;
strncpy(d.name, dirbuf.d_name, DIRSIZ);
d.name[DIRSIZ] = '\0'; /* ensure termination */
return &d;
}
return NULL;
}
我认为,与read()
, dp->fd
是目录的文件描述符。 作者使用read()
直接从目录文件中直接获取struct direct
。
但是,在Ubuntu中,无法读取目录文件。 当我尝试读取目录时,我感到有些奇怪。
我在APUE中读到,在某些系统中,不允许执行此操作。 那么还有其他方法可以实现我自己的readdir()
吗?
您正在查看40年前的代码。 目录根本没有像在任何现代平台上那样实现。 如果确实需要编写代码来操作文件系统,请阅读文件系统的文档(如果在Linux上,请阅读ext4)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.