[英]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.