I have to use the dirent.h in some of my C projects. According to various different descriptions found online, I have come to a vague idea that directory entry is a data structure, which tells us everything about a file. What exactly is a directory entry?
3 Answers
Not everything about the file, most of the metadata about the file is stored within the file inode, not the directory entry. The directory entry is just a struct of inode and filename - just enough information to translate from a filename to an inode and get to the actual file.
You can safely imagine a directory as a dictionary:
filename1 :> inode1
filename2 :> inode2
....
Then you just follow the inode number (basically the unique address of a inode -- a sort of pointer) and find all the permissions, ownership data, dates, extended attributes, and of course the contents of the file (if it's a file). Of course the directory entry can also be another directory, symbolic link, device node or anything like that. You have to go there to figure that out.
Directory Entry is basically the mapping of filename to its inode. The user generally accesses the file by its name, however such filenames are not understood by the kernel.
The kernel identifies a file using the inode which is unique for a file.
This inode basically contains all the data of the file except its name and the actual data in the file. Such mapping of the filename to its inode is maintained in the data structure called directory entry.
Remember that many entries (in the same or different directories) may identify the same file (same inode). So, given a name, you can obtain its inode easily; given an inode, finding the names is much harder (and the find
utility is the tool for this).
-
@toby
what does the last line edited by you exactly mean? Can you please elaborate it with an example? Commented Sep 8, 2015 at 16:57 -
It was just a throwaway comment that filenames and files aren't a one-to-one mapping. Some people seem to expect that they are. I wouldn't have bothered, but the spelling fix was too small on its own. Commented Sep 8, 2015 at 17:03
From Advanced Programming in the Unix Environment (APUE) §1.4:
What is a directory?
A directory is a file that contains directory entries.
What is a directory entry?
Logically, we can think of each directory entry as containing a filename along with a structure of information describing the attributes of the file. The attributes of a file are such things as the type of file (regular file, directory), the size of the file, the owner of the file, permissions for the file (whether other users may access this file), and when the file was last modified. The
stat
andfstat
functions return a structure of information containing all the attributes of a file.
For related material you can read §4.14 from APUE.
struct dirent
in/usr/include/dirent.h