K&R第8章,readdirfunction

我坚持这个function(在K&R第8章的fsize()例子中找到):

 #include  /* 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; } 

在这个函数中, DirentDIR是由K&R编写的自定义结构(不是在dirent.h中找到的结构):

 typedef struct { /* portable directory entry */ long ino; /* inode number */ char name[NAME_MAX+1]; /* name + '\0' terminator */ } Dirent; typedef struct { int fd; Dirent d; } DIR; 

当我使用书中的代码时,它运行正常,但有两个问题(问题):

  • 文件列表过程不会递归发生。 它只适用于当前目录一次。
  • 我无法理解上面带有read()函数的行。
    1)如果dp->fd是目录, read()将返回errno 21(目录错误),
    2) read() )如何填充内存结构dirbuf ,它是否只能读取某些类型的字符/字节?

谢谢。

想一想递归结构的成本。 对于每个dirent,您需要一个子目录列表。 这大大增加了你的内存需求,以及内存分配的复杂性(不能再使用堆栈分配的结构,你必须使用malloc / free )代码。

因此,我说#1无效。

不完全确定这是否是作业,但我不能重现#2,所以现在我将不管它。

  1. 调用该函数一次返回“下一个”目录条目。 它旨在被重复调用 – 每个目录条目一次。
  2. read syscall(在unistd.h中声明)不能给出目录文件描述符。 这很可能是一种不同的“读”function。 dirbuf在函数中声明,因此它不是只读的。