[英]K&R chapter 8, readdir function
我坚持这个功能(在K&R第8章的fsize()
例子中找到):
#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;
}
在这个函数中, Dirent
和DIR
是由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()
函数的行。 dp->fd
是目录, read()
将返回errno 21(目录错误), read()
)如何填充内存结构dirbuf
,它是否只能读取某些类型的字符/字节? 谢谢。
想一想递归结构的成本。 对于每个dirent,您需要一个子目录列表。 这大大增加了你的内存需求,以及你的内存分配的复杂性(不能再使用堆栈分配的结构,你必须使用malloc
/ free
)代码。
出于这个原因,我说#1无效。
不完全确定这是否是作业,但我不能重现#2,所以现在我将不管它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.