开发者

How do I read a directory as a file in Unix?

开发者 https://www.devze.com 2022-12-10 04:20 出处:网络
I understand that a directory is just a file in unix that contains the inode numbers and names of the files within. How do I take a look at this? I can\'t use cat or less on a directory, and opening i

I understand that a directory is just a file in unix that contains the inode numbers and names of the files within. How do I take a look at this? I can't use cat or less on a directory, and opening it in vi just shows me 开发者_StackOverflow中文版a listing of the files...no inode numbers.


Since this is a programming question (it is a programming question, isn't it?), you should check out the opendir, readdir and closedir functions. These are part of the Single UNIX Spec.

#include <sys/types.h>
#include <dirent.h>

DIR *opendir (const char *dirname);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

The dirent.h file should have the structure you need, containing at least:

char   d_name[]    name of entry
ino_t  d_ino       file serial number

See here for the readdir manpage - it contains links to the others.

Keep in mind that the amount of information about a file stored in the directory entries for it is minimal. The inode itself contains the stuff you get from the stat function, things like times, size, owner, permissions and so on, along with the all-important pointers to the actual file content.


In the old days - Version 7, System III, early System V - you could indeed open a directory and read the contents into memory, especially for the old Unix file system with 2-byte inode numbers and a limit of 14 bytes on the file name.

As more exotic file systems became more prevalent, the opendir(), readdir(), closedir() family of function calls had to be used instead because parsing the contents of a directory became increasingly non-trivial.

Finally, in the last decade or so, it has reached the point where on most systems, you cannot read the directory; you can open it (primarily so operations such as fchdir() can work), and you can use the opendir() family of calls to read it.


It looks like the stat command might be in order. From the article:

stat /etc/passwd

    File: `/etc/passwd'
    Size: 2911                Blocks: 8 IO    Block: 4096 regular file
    Device: fd00h/64768d      Inode: 324438   Links: 1
    Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
    Access: 2008-08-11 05:24:17.000000000 -0400
    Modify: 2008-08-03 05:11:05.000000000 -0400
    Change: 2008-08-03 05:11:05.000000000 -0400
0

精彩评论

暂无评论...
验证码 换一张
取 消