Search code examples
unixinodedir

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


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.


Solution

  • 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.