私はこの関数で立ち往生しています(fsize()
K&Rの第8章の例にあります):
#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
の andDIR
は、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;
本のコードを使用すると問題なく動作しますが、2 つの問題 (質問) がありました。
- ファイルの一覧表示プロセスは再帰的に発生しません。現在のディレクトリに一度だけ適用されます。
read()
上記の関数の行がわかりません。
1)dp->fd
ディレクトリの場合は、read()
errno 21 (ディレクトリ エラー) を返します
。2) メモリ構造をどのread()
ように埋めることができdirbuf
ますか? ある種の文字/バイトのみを読み取ることを想定していませんか?
ありがとう。