Lesson 3 · Files, storage, I/O, and protection

Directory Structure in OS

A directory maps names to files. How directories may nest and share files decides how users organise data, how paths work, and what deletion has to check.

Directory Structure in OS concept diagramFour panels. Single-level: one directory holding every file. Two-level: a master directory with one directory per user. Tree-structured: nested subdirectories. Acyclic graph: a tree in which one file is reachable from two directories through a link.single-level directorydircatboatestdataevery file in one directory; names must be uniquetwo-level directoryMFDuser1user2user3atestadataxone directory per user; no subdirectoriestree-structured directory/binhomelscpanabobsubdirectories to any depth; paths name filesacyclic-graph directory/anabobnotesplantodoa file shared by two directories via a link
1

What Is a Directory Structure?

  1. Search – find the entry for a given name.
  2. Create – add an entry for a new file.
  3. Delete – remove an entry, and the file if nothing else names it.
  4. List – show every entry in a directory.
  5. Rename – change the name in an entry without touching the file.
  6. Traverse – visit every directory and file below a point, as a backup does.

A directory is a symbol table that the file system keeps on disk. Each entry maps a file name to the file's file control block (an inode on Unix), which holds its size, owner, permissions and the location of its data. A directory is itself stored as a file whose content is these entries.

The directory structure is the shape these tables form: whether there is one directory or many, whether directories can contain directories, and whether one file can appear in more than one place. There are five classic structures, each fixing a limitation of the one before it. Whichever is used, it must support the six operations listed above.

  • Entry = name + pointer to the file control block
  • Directories are files that hold entries
  • The structure decides naming, grouping and sharing
2

Single-Level Directory

In a single-level directory every file on the system lives in one directory. It is the simplest possible scheme and was used by early microcomputer systems.

It breaks down as soon as there are many files or more than one user. Every name must be unique across the whole system, so two users cannot both have a file called test, and there is no way to group related files together.

  • Advantage: simple to implement, fast to search when small
  • Disadvantage: names must be unique system-wide
  • Disadvantage: no grouping; a long flat list of everything
  • Disadvantage: no per-user separation
3

Two-Level Directory Structure

A two-level directory gives each user a user file directory (UFD). A master file directory (MFD), indexed by user name, points to every UFD. When a user refers to a file, only their own UFD is searched, so different users can reuse the same names.

A file is named by a path of two parts, such as user2/data. This isolates users well but makes cooperation awkward: sharing a file means naming another user's directory, and a user still cannot organise their own files into groups, because a UFD cannot contain directories.

  • MFD → one UFD per user → files
  • Same file name allowed for different users
  • Search is faster: only one user's directory
  • No subdirectories, and sharing between users is clumsy
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Directory entryA name paired with a pointer to a file control block.
  • MFD / UFDMaster file directory and user file directory in the two-level scheme.
  • Path nameAbsolute from /, or relative from the current working directory.
  • Link countHow many directory entries name a file; it is freed at 0.

Operations and costs

  • Path lookupOne directory search per component.
  • Hard linkAdd an entry, increment the link count; no data copied.
  • UnlinkRemove an entry, decrement the count, free the file at 0.
  • Garbage collectionMark from the root and free the unmarked: needed only when cycles exist.

Related lessons

  • File SystemsWhere directories sit among files, metadata and free space.
  • Inodes in OSThe file control block a directory entry points to.
  • File Allocation MethodsHow the file's data blocks are laid out once found.
  • TreesThe data structure a tree-structured directory is.
Implementation

Paths, links and deletion in a directory tree

class File:
    def __init__(self, inode):
        self.inode = inode
        self.links = 0  # how many directory entries name this file


class Directory:
    def __init__(self, parent=None):
        self.entries = {}  # name -> Directory or File
        self.parent = parent if parent is not None else self


class FileSystem:
    def __init__(self):
        self.root = Directory()
        self.next_inode = 10

    def resolve(self, path, cwd):
        node = self.root if path.startswith("/") else cwd
        for part in path.strip("/").split("/"):
            if part in ("", "."):
                continue
            if not isinstance(node, Directory):
                raise NotADirectoryError(path)
            if part == "..":
                node = node.parent
            elif part in node.entries:
                node = node.entries[part]
            else:
                raise FileNotFoundError(f"{path}: no entry '{part}'")
        return node

    def split(self, path, cwd):
        head, _, name = path.rstrip("/").rpartition("/")
        parent = self.resolve(head or ("/" if path.startswith("/") else "."), cwd)
        return parent, name

    def mkdir(self, path, cwd):
        parent, name = self.split(path, cwd)
        parent.entries[name] = Directory(parent)

    def create(self, path, cwd):
        parent, name = self.split(path, cwd)
        f = File(self.next_inode)
        self.next_inode += 1
        f.links = 1
        parent.entries[name] = f
        return f

    def link(self, target, path, cwd):
        f = self.resolve(target, cwd)
        if isinstance(f, Directory):
            raise PermissionError("hard links to directories would allow cycles")
        parent, name = self.split(path, cwd)
        parent.entries[name] = f
        f.links += 1

    def unlink(self, path, cwd):
        parent, name = self.split(path, cwd)
        f = parent.entries.pop(name)
        f.links -= 1
        return "freed" if f.links == 0 else f"kept, {f.links} link(s) left"


fs = FileSystem()
root = fs.root
for d in ["/home", "/etc", "/home/ana", "/home/bob", "/home/ana/src"]:
    fs.mkdir(d, root)
for f in ["/etc/hosts", "/home/ana/notes.txt", "/home/bob/todo.txt", "/home/ana/src/main.c"]:
    fs.create(f, root)

cwd = fs.resolve("/home/ana", root)
todo = fs.resolve("/home/bob/todo.txt", cwd)
print("/home/bob/todo.txt -> inode", todo.inode)
print("src/main.c -> inode", fs.resolve("src/main.c", cwd).inode)
print("../bob/todo.txt is the same file:", fs.resolve("../bob/todo.txt", cwd) is todo)

try:
    fs.resolve("/home/carl/x", cwd)
except FileNotFoundError as error:
    print("Error:", error)

fs.link("/home/bob/todo.txt", "todo.txt", cwd)
print("After ln, link count =", todo.links)
print("rm /home/bob/todo.txt:", fs.unlink("/home/bob/todo.txt", cwd))
print("rm todo.txt:", fs.unlink("todo.txt", cwd))

try:
    fs.link("/home", "src/up", cwd)
except PermissionError as error:
    print("Error:", error)
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

struct Node {
    bool isDir;
    int inode = 0;
    int links = 0;  // for files: how many directory entries name this file
    Node* parent = nullptr;
    std::map<std::string, std::shared_ptr<Node>> entries;  // for directories
    explicit Node(bool dir) : isDir(dir) {}
};
using Ptr = std::shared_ptr<Node>;

class FileSystem {
public:
    Ptr root = std::make_shared<Node>(true);

    FileSystem() { root->parent = root.get(); }

    Node* resolve(const std::string& path, Node* cwd) {
        Node* node = path[0] == '/' ? root.get() : cwd;
        std::stringstream parts(path);
        std::string part;
        while (std::getline(parts, part, '/')) {
            if (part.empty() || part == ".") continue;
            if (!node->isDir) throw std::runtime_error(path + ": not a directory");
            if (part == "..") {
                node = node->parent;
            } else if (node->entries.count(part)) {
                node = node->entries[part].get();
            } else {
                throw std::runtime_error(path + ": no entry '" + part + "'");
            }
        }
        return node;
    }

    void mkdir(const std::string& path, Node* cwd) {
        auto [parent, name] = split(path, cwd);
        auto dir = std::make_shared<Node>(true);
        dir->parent = parent;
        parent->entries[name] = dir;
    }

    Node* create(const std::string& path, Node* cwd) {
        auto [parent, name] = split(path, cwd);
        auto file = std::make_shared<Node>(false);
        file->inode = nextInode++;
        file->links = 1;
        parent->entries[name] = file;
        return file.get();
    }

    void link(const std::string& target, const std::string& path, Node* cwd) {
        Node* t = resolve(target, cwd);
        if (t->isDir) throw std::runtime_error("hard links to directories would allow cycles");
        auto [targetParent, targetName] = split(target, cwd);
        auto [parent, name] = split(path, cwd);
        parent->entries[name] = targetParent->entries[targetName];
        t->links++;
    }

    std::string unlink(const std::string& path, Node* cwd) {
        auto [parent, name] = split(path, cwd);
        Ptr file = parent->entries[name];
        parent->entries.erase(name);
        file->links--;
        return file->links == 0 ? "freed" : "kept, " + std::to_string(file->links) + " link(s) left";
    }

private:
    int nextInode = 10;

    std::pair<Node*, std::string> split(const std::string& path, Node* cwd) {
        size_t cut = path.find_last_of('/');
        if (cut == std::string::npos) return {cwd, path};
        std::string head = path.substr(0, cut);
        return {resolve(head.empty() ? "/" : head, cwd), path.substr(cut + 1)};
    }
};

int main() {
    FileSystem fs;
    Node* root = fs.root.get();
    for (std::string d : {"/home", "/etc", "/home/ana", "/home/bob", "/home/ana/src"}) {
        fs.mkdir(d, root);
    }
    for (std::string f : {"/etc/hosts", "/home/ana/notes.txt", "/home/bob/todo.txt",
                          "/home/ana/src/main.c"}) {
        fs.create(f, root);
    }

    Node* cwd = fs.resolve("/home/ana", root);
    Node* todo = fs.resolve("/home/bob/todo.txt", cwd);
    std::cout << "/home/bob/todo.txt -> inode " << todo->inode << '\n';
    std::cout << "src/main.c -> inode " << fs.resolve("src/main.c", cwd)->inode << '\n';
    std::cout << "../bob/todo.txt is the same file: "
              << (fs.resolve("../bob/todo.txt", cwd) == todo ? "True" : "False") << '\n';

    try {
        fs.resolve("/home/carl/x", cwd);
    } catch (const std::runtime_error& error) {
        std::cout << "Error: " << error.what() << '\n';
    }

    fs.link("/home/bob/todo.txt", "todo.txt", cwd);
    std::cout << "After ln, link count = " << todo->links << '\n';
    std::cout << "rm /home/bob/todo.txt: " << fs.unlink("/home/bob/todo.txt", cwd) << '\n';
    std::cout << "rm todo.txt: " << fs.unlink("todo.txt", cwd) << '\n';

    try {
        fs.link("/home", "src/up", cwd);
    } catch (const std::runtime_error& error) {
        std::cout << "Error: " << error.what() << '\n';
    }
}
import java.util.HashMap;
import java.util.Map;

public class Main {
    static class Node {
        final boolean isDir;
        int inode;
        int links; // for files: how many directory entries name this file
        Node parent;
        final Map<String, Node> entries = new HashMap<>(); // for directories

        Node(boolean isDir) {
            this.isDir = isDir;
        }
    }

    static class FileSystem {
        final Node root = new Node(true);
        int nextInode = 10;

        FileSystem() {
            root.parent = root;
        }

        Node resolve(String path, Node cwd) {
            Node node = path.startsWith("/") ? root : cwd;
            for (String part : path.split("/")) {
                if (part.isEmpty() || part.equals(".")) continue;
                if (!node.isDir) throw new IllegalStateException(path + ": not a directory");
                if (part.equals("..")) {
                    node = node.parent;
                } else if (node.entries.containsKey(part)) {
                    node = node.entries.get(part);
                } else {
                    throw new IllegalStateException(path + ": no entry '" + part + "'");
                }
            }
            return node;
        }

        Object[] split(String path, Node cwd) {
            int cut = path.lastIndexOf('/');
            if (cut < 0) return new Object[] {cwd, path};
            String head = path.substring(0, cut);
            return new Object[] {resolve(head.isEmpty() ? "/" : head, cwd), path.substring(cut + 1)};
        }

        void mkdir(String path, Node cwd) {
            Object[] at = split(path, cwd);
            Node dir = new Node(true);
            dir.parent = (Node) at[0];
            ((Node) at[0]).entries.put((String) at[1], dir);
        }

        void create(String path, Node cwd) {
            Object[] at = split(path, cwd);
            Node file = new Node(false);
            file.inode = nextInode++;
            file.links = 1;
            ((Node) at[0]).entries.put((String) at[1], file);
        }

        void link(String target, String path, Node cwd) {
            Node t = resolve(target, cwd);
            if (t.isDir) throw new IllegalStateException("hard links to directories would allow cycles");
            Object[] at = split(path, cwd);
            ((Node) at[0]).entries.put((String) at[1], t);
            t.links++;
        }

        String unlink(String path, Node cwd) {
            Object[] at = split(path, cwd);
            Node file = ((Node) at[0]).entries.remove((String) at[1]);
            file.links--;
            return file.links == 0 ? "freed" : "kept, " + file.links + " link(s) left";
        }
    }

    public static void main(String[] args) {
        FileSystem fs = new FileSystem();
        Node root = fs.root;
        for (String d : new String[] {"/home", "/etc", "/home/ana", "/home/bob", "/home/ana/src"}) {
            fs.mkdir(d, root);
        }
        for (String f : new String[] {"/etc/hosts", "/home/ana/notes.txt", "/home/bob/todo.txt", "/home/ana/src/main.c"}) {
            fs.create(f, root);
        }

        Node cwd = fs.resolve("/home/ana", root);
        Node todo = fs.resolve("/home/bob/todo.txt", cwd);
        System.out.println("/home/bob/todo.txt -> inode " + todo.inode);
        System.out.println("src/main.c -> inode " + fs.resolve("src/main.c", cwd).inode);
        System.out.println("../bob/todo.txt is the same file: "
                + (fs.resolve("../bob/todo.txt", cwd) == todo ? "True" : "False"));

        try {
            fs.resolve("/home/carl/x", cwd);
        } catch (IllegalStateException error) {
            System.out.println("Error: " + error.getMessage());
        }

        fs.link("/home/bob/todo.txt", "todo.txt", cwd);
        System.out.println("After ln, link count = " + todo.links);
        System.out.println("rm /home/bob/todo.txt: " + fs.unlink("/home/bob/todo.txt", cwd));
        System.out.println("rm todo.txt: " + fs.unlink("todo.txt", cwd));

        try {
            fs.link("/home", "src/up", cwd);
        } catch (IllegalStateException error) {
            System.out.println("Error: " + error.getMessage());
        }
    }
}
Watch it run

Step through it

Running on cwd = /home/ana; resolve /home/bob/todo.txt, src/main.c, ../bob/todo.txt

/home/etc/ana/cwdbob/hostsnotes.txtsrc/todo.txtmain.ceach entry maps a name to a directory or a file
Step 1

A tree-structured directory

Every directory is a file whose contents are entries: a name and a pointer to another directory or file. Rectangles are directories, rounded boxes are files. The current working directory (cwd) of this shell is /home/ana.

Output
1 / 14
4

Tree-Structured Directory

A tree-structured directory lets a directory contain other directories, to any depth. This is the structure users know from every modern system. There is one root, every file has a unique path from it, and users create subdirectories to group their work.

Each process has a current working directory (cwd). An absolute path starts with / and is resolved from the root. A relative path is resolved from the cwd, and the special entries . (this directory) and .. (the parent) let it move up as well as down. Resolving a path costs one directory lookup per component, which is why file systems cache recent lookups.

Deleting a directory raises a policy question: refuse unless it is empty, or delete everything under it (rm -r). Most systems require an explicit recursive delete.

Resolving paths from cwd = /home/ana
PathKindStarts atResolves to
/home/bob/todo.txtabsolute//home/bob/todo.txt
src/main.crelative/home/ana/home/ana/src/main.c
../bob/todo.txtrelative/home/ana/home/bob/todo.txt
/home/carl/xabsolute/error: carl does not exist
  • Subdirectories to any depth, one root
  • Absolute paths start at /, relative paths at the cwd
  • . is the current directory, .. is the parent
  • Each file has exactly one path: sharing is not possible yet
5

Acyclic-Graph Directory

An acyclic-graph directory allows a file (or subdirectory) to appear in more than one directory, so two users working on one project can each have it in their own tree. The structure is a graph because a node can have several parents, but it has no cycles.

Sharing is implemented with links. A hard link is a second directory entry pointing at the same file control block; the names are equal and indistinguishable. A symbolic (soft) link is a small file containing a path, which is resolved again each time it is used.

Sharing makes deletion harder. If one name is removed and the file is freed, the other names become dangling pointers. Hard links solve this with a reference count (the link count) in the inode: deleting a name decrements it, and the file is freed only when it reaches 0. A symbolic link to a deleted file is simply left dangling and fails when followed.

Hard links against symbolic links
PropertyHard linkSymbolic link
What it storespointer to the same inodea path string
Target deletedfile survives while count > 0link dangles
Across file systemsnoyes
To a directorynot allowed (Unix)allowed, skipped by traversal
  • Files can be shared: one file, several names
  • Hard links: same inode, deletion by link count
  • Symbolic links: a stored path, may dangle
  • Traversal must not count a shared file twice
6

General Graph Directory

If links to directories are allowed without restriction, the structure becomes a general graph that can contain cycles, such as a subdirectory linking back to its own ancestor.

Cycles cause two problems. A recursive search or backup can loop forever unless it tracks visited directories. And reference counts stop working: a cycle of directories that nothing else points to still has non-zero counts, so it is never freed, and reclaiming it needs garbage collection, a full traversal that marks everything reachable from the root. Because that is expensive, Unix forbids hard links to directories and traversal tools ignore symbolic links, which keeps the real structure acyclic.

  • Cycles make traversal loop unless visited nodes are tracked
  • Unreachable cycles keep non-zero counts: garbage collection needed
  • Most systems prevent cycles instead of handling them
7

Directory Structures Compared

Each structure adds one capability to the one before it, and the last adds a problem instead. Tree-structured directories with acyclic sharing through links are what every modern operating system uses.

The five directory structures
StructureGroupingSame name for different usersSharingMain drawback
Single-levelnonotrivially, everything is sharedname clashes
Two-levelper user onlyyesawkwardno subdirectories
Treeany depthyesnoa file has one path only
Acyclic graphany depthyesvia linksdeletion needs reference counts
General graphany depthyesunrestrictedcycles need garbage collection
  • Single-level → two-level: separate users
  • Two-level → tree: group files in subdirectories
  • Tree → acyclic graph: share files through links
  • Acyclic → general graph: cycles, usually forbidden