Skip to content

File System ​

A file system is the operating system's way of organizing the countless files on a storage device so they can be found easily, kept safely, and managed. A hard disk or SSD holds nothing but a huge pile of 0s and 1s, but thanks to the file system, you can handle files by name and folder, like "report.txt in the Documents folder."

At a Glance ​

  • Analogy: the storage device is a giant warehouse, and the file system is the warehouse's inventory ledger and shelving rules. Because the ledger records which shelf each item (data) is on, what it is called, and when it came in, you can find what you want right away no matter how big the warehouse is.
  • The part corresponding to the ledger is the meta area, and the shelves where the actual items sit are the data area.
  • The directory structure actually used on Linux (/home, /etc, etc.) and file permissions are covered hands-on in File System and Permissions. This article looks at file systems from the operating systems theory side.

Characteristics ​

  • It runs in kernel space. When a program opens or reads a file, it does not touch the disk directly; it asks the kernel through a system call.
  • Its goal is to make CRUD operations smooth: creating (Create), reading (Read), modifying (Update), and deleting (Delete) files.
  • It has a hierarchical directory structure (folders inside folders).
  • You can have one per disk partition. For example, you can split one disk in two and use ext4 on one side and NTFS on the other.

Roles ​

RoleDescription
File managementCreating, naming, deleting, and finding files
Secondary storage managementTracking which disk blocks are free and which are in use
Guaranteeing file integrityProtecting files from corruption even after a power failure or error (e.g. journaling)
Providing access methodsProviding ways to read and write, such as sequential access and direct access

Why It Was Developed ​

  • File management: organizes countless files systematically by name and directory.
  • Using hard disk capacity efficiently: tracks free space so files are stored without waste.
  • Reducing the speed gap between the hard disk and main memory: the disk is much slower than memory. So the file system also uses a buffer cache that temporarily keeps frequently used file contents in memory, so it doesn't have to go all the way to the disk every time.

Structure ​

A file system is divided into two main areas.

AreaWhat it holdsAnalogy
Meta areaInformation about files, such as file name, location (which blocks it is in), size, creation and modification times, and whether it has been deletedThe warehouse ledger
Data areaThe actual contents of filesThe shelves where items sit

On Linux, the metadata of a single file is stored in a structure called an inode. When a file is deleted, the actual contents are often not erased right away; the file is just marked as "deleted" in the meta area. That is why recovery programs can bring deleted files back.

File Access Methods ​

1. Sequential Access ​

The simplest method: reading and writing in order from the beginning. Most operations are read and write.

text
start                        current position          end
 │                               │                      │
 ▼                               ▼                      ▼
[record0][record1][record2][record3][record4][record5]...
   ◀── rewind              reading or writing ──▶ moves forward
  • A file has a pointer that indicates the current position. A read or write system call reads or writes at that position, and the pointer moves forward automatically.
  • To go back, you have to rewind by a set distance (offset).
  • It works like listening to a cassette tape, so it is also called the tape model.

Sequential access file: reading or writing at the current position moves it forward, and rewind returns to the beginning

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

2. Direct Access ​

A method that jumps straight to the desired position regardless of order to read and write. It is also called Random Access.

text
[block0][block1][block2][block3][block4][block5][block6]...
           ▲                       ▲       ▲
           │                       │       │
     read block 1         read block 4  write block 5   ← jump directly, in any order
  • The file is viewed as fixed-size blocks (records) lined up by number, and requests look like "read block n."
  • If you keep just one variable (cp) pointing to the current position, a direct access file can easily imitate sequential access: just read while increasing cp by 1 each time. On the other hand, imitating direct access using only sequential access is inefficient.
  • It is widely used in databases, which need fast access to a lot of information.

The table below shows how a direct access file imitates sequential access. Going back to the start (reset) is cp = 0, and reading the next item (read_next) means reading block cp and then increasing cp by 1.

How a direct access file imitates sequential access's reset, read_next, and write_next using a current position variable cp

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

3. Indexed Access ​

Built on direct access, this method creates an index first, finds the position in the index, and then goes straight to that block.

text
Index file                        Actual file
┌────────┬─────────┐
│ Name   │ Block # │            [block0][block1][block2][block3]...
├────────┼─────────┤                                     ▲
│ choi   │    3    │ ────────────────────────────────────┘
│ kim    │    0    │
│ park   │    2    │
└────────┴─────────┘
  • Like the index at the back of a book, it helps you quickly find what you want in a large file.
  • Database indexes use the same idea. See the Index article.

In the figure below, Smith is looked up in the index file, and the record number written there leads directly to the matching record in the actual file.

Following the number found by last name in the index file straight to the smith, john record in the actual file

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

Comparing Them in Code ​

Five student records were saved to a file as fixed-length 16-byte records and then read in three ways. seek() is the function that moves the file pointer to a desired position.

python
RECORD = 16  # size of one record (fixed at 16 bytes)

# save 5 students' records to a file as fixed-length records
with open("students.dat", "w", encoding="ascii") as f:
    for i, name in enumerate(["kim", "lee", "park", "choi", "jung"]):
        f.write(f"{i:02d} {name}".ljust(RECORD - 1) + "\n")

# 1) sequential access: read in order from the beginning
with open("students.dat", encoding="ascii") as f:
    print("Sequential access:", [line.strip() for line in f])

# 2) direct access: jump straight to record 3
with open("students.dat", encoding="ascii") as f:
    f.seek(3 * RECORD)                 # move to the start of record 3
    print("Direct access (record 3):", f.read(RECORD).strip())

# 3) indexed access: check the name -> record number index first, then go straight there
index = {"kim": 0, "lee": 1, "park": 2, "choi": 3, "jung": 4}
with open("students.dat", encoding="ascii") as f:
    f.seek(index["park"] * RECORD)
    print("Indexed access (park):", f.read(RECORD).strip())
text
Sequential access: ['00 kim', '01 lee', '02 park', '03 choi', '04 jung']
Direct access (record 3): 03 choi
Indexed access (park): 02 park

Directory Structures ​

A directory (folder) is a special file that groups and organizes files. There are several structures depending on how it is organized.

Single-Level Directory ​

The simplest structure, where all files are in a single directory.

text
       [ root directory ]
     /    |     |     \
  a.txt  b.txt  c.py  data.csv
  • Every file must have a different name. Even different users cannot use the same name.
  • When there are many files, management becomes very difficult.

A single-level directory where all files such as cat, bo, a, and test sit side by side under one directory

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

Two-Level Directory ​

Each user gets their own separate directory.

text
                 [ MFD ]
            /       |       \
       [kim UFD] [lee UFD] [park UFD]
        /    \       |        |
    a.txt  b.txt   a.txt    c.py     ← kim and lee can both use the name a.txt
  • MFD (Master File Directory): the top-level directory, indexed by user name or account number
  • UFD (User File Directory): the file directory of a single user
  • Different users can use the same file name. But within one user, folders still cannot be divided further.

In the figure below, users 1, 2, 3, and 4 all have a file with the same name a, but that is fine because they are in different UFDs.

A two-level directory where UFDs for users 1 to 4 sit under the MFD, and each user can have their own files named a, test, and data

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

Tree-Structured Directory ​

A multi-level structure that extends the two-level structure so you can create as many directories inside directories as you want. Most operating systems we use today are based on this structure.

text
                 /
          /      |      \
       home     etc     usr
        |                |
       kim              bin
      /   \
  docs    photo
   |
 report.txt          → path: /home/kim/docs/report.txt
  • A directory is also treated as a file. Each entry has one bit that distinguishes whether it is a regular file (0) or a directory file (1).
  • A path is written either as an absolute path starting from the root (/home/kim/docs) or a relative path starting from the current location (docs/report.txt).

A tree structure where spell, bin, and programs directories sit under root, with directories and files branching out over several levels below

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

Graph-Structured Directory ​

A structure that adds links to the tree structure so a single file or directory can be pointed to from several places. Links on Linux (ln) are exactly this.

text
        /
     /     \
   kim     lee
    |       |
  project ◀─┘ (link)     ← kim and lee share the same project folder
    |
  main.py

If links are allowed freely, cycles can form. For example, if b is inside a, and b contains a link pointing back to a, a program that walks folders all the way down will loop forever. There are two ways to prevent this.

MethodDescription
Prevent cycles from the start (acyclic graph)Block links that point to subdirectories and allow links to files only. Or skip links when traversing instead of following them
Allow cycles and clean up (general graph)Use garbage collection to walk the whole file system, mark everything reachable, and clean up whatever is not marked (nothing points to it)

Linux is closer to the first approach. Hard links cannot be created for directories, and tools like find do not follow symbolic links to directories by default.

The figure below is a general graph structure that allows cycles. The avi entry inside the book directory under avi points back to book, creating a cycle, and the book of avi and jim point to the same directory.

A general graph directory where an entry inside avi's book directory points back to book, creating a cycle, and several directories point to the same files

Image source: noep blog, File system notes (original source: Silberschatz et al., Operating System Concepts)

Comparing Directory Structures ​

StructureCharacteristicsLimitations
Single-levelAll files in one directoryNames must not overlap; no way to organize
Two-levelOne directory per userCan't divide further within a user
TreeDirectories inside directoriesSharing files is difficult
GraphTree + sharing via linksNeeds a mechanism to prevent or clean up cycles

Summary ​

ConceptSummary for non-CS majors
File systemWarehouse rules that let you find and manage files on a storage device by name and folder
Meta areaThe ledger recording information such as file name, location, size, and times
Data areaWhere the actual contents of files are stored
Sequential accessReading in order from the beginning, like a tape
Direct accessJumping straight to the block number you want and reading it. Widely used in databases
Indexed accessFinding the position in an index first, then going straight there
Single-level directoryAll files in one folder. Names must not overlap
Two-level directoryOne folder per user
Tree directoryFolders inside folders. The structure used most today
Graph directorySharing from several places via links. Watch out for cycles

Reference: noep - File System