0

私はこの関数で立ち往生しています(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ますか? ある種の文字/バイトのみを読み取ることを想定していませんか?

ありがとう。

4

2 に答える 2

1

再帰構造のコストについて少し考えてみてください。ディレクトリごとに、サブディレクトリのリストが必要になります。これにより、メモリ要件が大幅に増加し、メモリ割り当てが複雑になります (スタック割り当て構造体は使用できなくなり、malloc/を使用する必要がありますfree) コード。

このため、#1 は無効であると言います。

これが宿題かどうかは完全にはわかりませんが、#2を再現できないので、今はそのままにしておきます.

于 2012-06-16T14:09:48.337 に答える
1
  1. 関数を 1 回呼び出すと、「次の」ディレクトリ エントリが返されます。これは、ディレクトリ エントリごとに 1 回ずつ、繰り返し呼び出されることを意図しています。
  2. read syscall (unistd.h で宣言されている) には、ディレクトリ ファイル記述子を指定できません。これはおそらく別の「読み取り」機能です。dirbuf は関数内で宣言されているため、読み取り専用ではありません。
于 2012-06-16T14:12:52.760 に答える