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

我的梦境 提交于 2019-11-28 06:36:33

问题


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 a listing of the files...no inode numbers.


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/1659071/how-do-i-read-a-directory-as-a-file-in-unix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!