[英]Passing argument to read function, from structures like (char *) &(struct)
阅读K&R书籍ANSI,并碰到无法理解的源代码,它与readdir
函数有关。 该代码很大。 就像这样:
typedef struct {
long ino;
char name[NAME_MAX+1];
} Dirent;
在readdir
函数中,我们有:
Dirent *dirbuf;
现在,有:
ignore what is this what is dis what is dis
while (read(dp->fd, (char *) &dirbuf , sizeof(dirbuf) ) == sizeof( dirbuf) )
问题是“什么是dis,这是什么”,请向我解释它的作用。 我一直在使用它来检查( char *
)是否在结构中搜索char *
并在查找时采用IT read
功能,但这不是吗? 您还可以解释该语句在检查时是否等于sizeof( dirbuf)
,为什么第三个参数不是sizeof(dirbuf->name)
? 这是我尝试的:
struct lele{
int dig;
char name[20];
};
int main(void)
{
struct lele p;
scanf("%d%s", (int *) &p, (char *) &p);
printf("name: %s ,,, dig : %d\n", p.name, p.dig);
return 0;
}
INPUT: 5 , green OUTPUT: name: n ,,, dig : 1701147239
还可以说明和OUTPUT吗? EDIT主流问题是为什么第二个参数不是dirbuf->name
? 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;
}
在过去(或K&R)时代,UFS(Unix文件系统)上的目录可以通过open()
, read()
, close()
read()
。 此外,文件名限制为14个字符,索引节点号限制为2个字节( unsigned short
)。 一个目录包含16个字节的条目:
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| inode | . | \0| \0| \0| \0| \0| \0| \0| \0| \0| \0| \0| \0| \0|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| inode | . | . | \0| \0| \0| \0| \0| \0| \0| \0| \0| \0| \0| \0|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| inode | f | i | l | e | n | a | m | e | \0| \0| \0| \0| \0| \0|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| inode | l | o | n | g | e | r | f | i | l | e | n | a | m | e |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 00000 | d | e | l | e | t | e | d | - | f | i | l | e | \0| \0|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| inode | o | t | h | e | r | n | a | m | e | \0| \0| \0| \0| \0|
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
请注意,最多可以包含14个字符,但此类名称不能以空值结尾。 删除的条目的inode编号为零,但名称未更改。 空填充与strncpy()
功能匹配(尽管不清楚strncpy()
实际用于执行此操作)。
更现代的文件系统允许使用可变长度的名称,并通过仅为名称分配所需的空间来避免浪费空间,并且它们使用大的inode编号。
问题中显示的代码是:
while (read(dp->fd, (char *)&dirbuf, sizeof(dirbuf)) == sizeof(dirbuf))
看起来像第一版。 在那个年代,没有void *
而char *
是通用指针。 这将执行read()
函数调用,将dirbuf
变量视为缓冲区。 sizeof(dirbuf)
给出变量的大小(以字节为单位)。 因此,这会将固定数量的字节读入变量。 read()
系统调用返回其读取的字节数。 如果这不是请求的数目,则可能是一个问题—可能是EOF(用零表示),或者是-1(文件描述符有问题),或者是小于请求的大小的数字(可能表示损坏了)。文件系统)。 因此,总的来说,循环将目录条目读取到结构变量dirbuf
。
我不相信结构中显示的大小( long
为4个字节,并且没有空填充)。 我必须看看他们在做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.