Why do directory listings contain the current (.) and parent (..) directory?

后端 未结 8 1166
面向向阳花
面向向阳花 2020-12-11 03:11

Whenever I list the contents of a directory with a function like readdir, the returned file names also include \".\" and \"..\". I have the suspicion that these are just nor

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 03:26

    I have the suspicion that these are just normal links in the file system and therefore indistinguishable from actual files

    They are. While you may perceive the file system as a hierarchy of "folders" "containing" folders, it is actually a doubly linked tree1, with directories being nodes and files being leafs. So, . and .. are needed links for accessing the leaves of the current node and for traversing the tree, and they are the same thing as all the other links.

    When you call readdir, you get all the places you can directly go to from the current node. If you do not want to list places that you perceive as "up", you have to sort them out yourself. You should write a little function for that, perhaps called readdir_down. I do not know in which order readdir lists the directories, but perhaps you can just throw away the first two entries.

    1) this is a first approximation, there are also "hard links" possible that make the tree actually a net.

提交回复
热议问题