Programming Search⌘K

Conceptintro

File system

Also called file system, filesystem, file tree, directory tree, volume, mount point, inode.

A file system keeps named files in a tree of directories on a volume. A program sees names, file types, file serial numbers and mount points, and not the blocks on the disk.

Applies to
core-languages

Idea

A disk holds blocks of bytes, but a program asks for docs/notes.txt. The file system is the layer between the two. It keeps files, gives them names in a tree of directories, and stores the attributes of each file, such as its type, its size and its permissions. A program uses only names and attributes. The file system decides where the bytes go.

import os
import shutil
import stat
from pathlib import Path

# A directory holds names. Each name refers to a file.
os.mkdir("docs")
Path("docs/notes.txt").write_text("hello\n", encoding="utf-8")
# A hard link is a second name for the same file.
os.link("docs/notes.txt", "copy-of-notes.txt")

for name in ["docs", "docs/notes.txt", "copy-of-notes.txt"]:
    st = os.stat(name)
    kind = "directory" if stat.S_ISDIR(st.st_mode) else "regular file"
    print(f"{name:18} {kind:13} {st.st_size if kind != 'directory' else '-':>3}")

# The device ID and the file serial number (inode number) identify a file.
a = os.stat("docs/notes.txt")
b = os.stat("copy-of-notes.txt")
print("same file:", (a.st_dev, a.st_ino) == (b.st_dev, b.st_ino))
print("names of the file:", a.st_nlink)

# The root directory is a mount point, and each file system has its own space.
print("/ is a mount point:", os.path.ismount("/"))
usage = shutil.disk_usage(".")
print("free space is known:", 0 < usage.free <= usage.total)
Output
docs               directory       -
docs/notes.txt     regular file    6
copy-of-notes.txt  regular file    6
same file: True
names of the file: 2
/ is a mount point: True
free space is known: True

The program makes a directory, a file in it, and a second name for the file. os.stat gives the attributes of the file that a name refers to. The two names give the same device ID and the same file serial number, so they are one file with two names, and the link count is 2. The file system does not store the name in the file. It stores the name in the directory. The last two lines show that the root directory is a mount point, and that the file system reports its free space.

How it works

Files. POSIX defines a file as "An object that can be written to, or read from, or both"1. Each file has a type. "File types include regular file, character special file, block special file, FIFO special file, symbolic link, socket, and directory"1. A regular file is "a randomly accessible sequence of bytes, with no further structure imposed by the system"1. So lines, records and formats are the work of the program, not of the file system.

Directories and names. A directory is "A file that contains directory entries", and "No two directory entries in the same directory have the same name"1. A directory entry, or hard link, is "An object that associates a filename with a file", and "Several directory entries can associate names with the same file"1. Because a directory can hold other directories, the names make a tree. A path such as a/b/c names a route through the tree: "Each filename in the pathname is located in the directory specified by its predecessor"2.

File serial numbers. The name is not the identity of a file. POSIX gives each file a file serial number, "A per-file system unique identifier for a file"1. Unix calls it the i-number. In the Unix paper, a directory entry "contains only a name for the associated file and a pointer to the file itself", and the pointer "is an integer called the i-number (for index number) of the file"3. The i-number selects the i-node, which holds the owner, the protection bits, the disk addresses, the size, the times and the number of links3. A file system is "A collection of files and certain of their attributes", and "It provides a name space for file serial numbers referring to those files"1. So an inode number is unique only inside one file system. POSIX requires that files are "uniquely identified by the combination of the st_ino and st_dev fields"4, that is, the inode number and the device ID together.

Mounts and volumes. A system has many file systems, but on Unix the program sees one tree. The mount operation puts the root of one file system at a directory of another. The Unix paper says that "mount replaces a leaf of the hierarchy tree (the ordinary file) by a whole new subtree (the hierarchy stored on the removable volume)"3. POSIX defines a mount point as "Either the system root directory or a directory for which the st_dev field of structure stat differs from that of its parent directory"1. Windows shows each volume with its own root, such as C:\. Microsoft says that "The highest level of organization in the file system is the volume", and "A file system resides on a volume"5.

File system types. Each volume is formatted with one file system type, such as FAT, exFAT, NTFS, APFS or ext36. The type decides the rules that a program can see: the longest name, the characters that a name can hold, case sensitivity, the resolution of the times, and the support for links and permissions. The site keeps the types as cards, not as pages.

File systems in a library. A language library gives one interface to many kinds of storage. In Java, a FileSystem "Provides an interface to a file system and is the factory for objects to access files and other objects in the file system"7, and a FileStore "represents a storage pool, device, partition, volume, concrete file system or other implementation specific means of file storage"8. Go says that "A file system can be provided by the host operating system but also by other packages"9. So a zip archive, a tree in memory and the files in a program can use the same calls as a disk.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CLibrary
C#Standard library
JavaScriptStandard library
TypeScriptStandard libraryTypeScript on Node.js uses the node:fs module, with the types from @types/node, so the calls are the calls of the JavaScript example. No example file exists.
GoStandard library
RustStandard library
KotlinStandard libraryThe kotlin.io.path package adds extension functions to java.nio.file.Path, so a Kotlin program uses the FileSystem, FileStore and Files classes of Java. No example file exists because kotlinc is not installed.
SQLDoes not applyA query works on tables. The database server keeps the tables in files, but the SQL language has no operations on files or directories.
BashNativeBash works with names in the file tree. The tests -d, -f and -ef are built in, and -ef is true when two names refer to the same device and inode numbers. The commands ls -i, ln, df and mount show the rest. No example file exists.
PowerShellNativeThe FileSystem provider shows the directories and files as drives such as C and Temp, and Get-Item, Get-ChildItem and Get-PSDrive work on them. No example file exists because pwsh is not installed.
HTMLDoes not applyA web page cannot see the file system of the user. An input element of type file lets the user choose files and give them to the page.
CSSDoes not applyStyle rules do not read, name or list files. A URL in a rule names a resource, not a file of the local file system.
Regular expressionsDoes not applyA regular expression matches text. It does not name, open or list files.
Language Verdict Mechanism
Python stdlib os.stat, os.scandir, os.link, os.statvfs, os.path.ismount, shutil.disk_usage; pathlib.Path
JavaScript stdlib Node.js node:fs: stat with dev, ino and nlink, readdir with withFileTypes, link, statfs
TypeScript stdlib the node:fs module of Node.js, with the types of @types/node
Java stdlib java.nio.file: FileSystem, FileStore, Files.isSameFile, the unix attribute view; the zip file system provider
Kotlin stdlib kotlin.io.path extensions on java.nio.file.Path, so the Java classes do the work
C# stdlib System.IO: DirectoryInfo, FileInfo, FileSystemInfo.LinkTarget, DriveInfo; .NET 10 has no method that makes a hard link
Go stdlib os.Stat, os.SameFile, os.Link; the io/fs interfaces with os.DirFS and testing/fstest.MapFS
Rust stdlib std::fs: metadata, read_dir, hard_link; std::os::unix::fs::MetadataExt for dev, ino and nlink
C library ISO C has fopen, remove, rename and tmpfile, and no directories; POSIX adds stat, link, statvfs and <dirent.h>
C++ stdlib std::filesystem: directory_iterator, equivalent, hard_link_count, space
Bash native the tests -d, -f and -ef; the commands ls -i, ln, df and mount
PowerShell native the FileSystem provider with drives such as C: and Temp:; Get-Item, Get-ChildItem, Get-PSDrive
SQL n/a a query works on tables; the database server keeps them in files, but SQL has no file operations
Regex n/a a pattern matches text, and it does not name or open files
HTML n/a a page cannot see the file system; <input type="file"> lets the user choose files and give them to the page
CSS n/a style rules do not read or name files, except the URLs of resources

Each general-purpose language reaches the file system through its standard library, which calls the operating system. C is the exception, because the ISO C library has only a few operations on files and none on directories, so C programs use POSIX or the Win32 API. In Bash, [[ a -ef b ]] is "True if file1 and file2 refer to the same device and inode numbers"10. In PowerShell, "The FileSystem drives are a hierarchical namespace containing the directories and files on your computer"11.

The example files show the same ideas in each language. Python and Rust show that a rename keeps the inode number, and Python and JavaScript read the free space of the file system with statvfs and statfs. Java writes a file into a zip archive with the same Files calls that it uses for the disk. Go walks a directory on the disk and a tree in memory with one function, because both are an fs.FS. C# makes a symbolic link, because .NET 10 has no method that makes a hard link. C uses stat, link and statvfs, and C++ uses std::filesystem, which "provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories"12.

PythonGitHub
import os
from pathlib import Path

root = Path("tree")
(root / "src").mkdir(parents=True)
(root / "src" / "main.txt").write_text("main\n", encoding="utf-8")
(root / "readme.txt").write_text("read me\n", encoding="utf-8")

# A directory is a list of names. scandir gives the type of each entry.
for entry in sorted(os.scandir(root), key=lambda e: e.name):
    print(entry.name, "dir" if entry.is_dir() else "file")

# A rename changes a name, not the file: the inode number stays.
before = (root / "readme.txt").stat().st_ino
(root / "readme.txt").rename(root / "README.txt")
print("same inode after rename:", (root / "README.txt").stat().st_ino == before)

# A hard link is one more name; samefile compares device and inode.
os.link(root / "src" / "main.txt", root / "main-link.txt")
print("samefile:", (root / "main-link.txt").samefile(root / "src" / "main.txt"))
print("links:", (root / "src" / "main.txt").stat().st_nlink)

# statvfs describes the file system that holds the path.
vfs = os.statvfs(root)
print("block size > 0:", vfs.f_frsize > 0)
print("free bytes for this user > 0:", vfs.f_bavail * vfs.f_frsize > 0)
Output
readme.txt file
src dir
same inode after rename: True
samefile: True
links: 2
block size > 0: True
free bytes for this user > 0: True
  • Verdict: stdlib. os.scandir gives the type of each entry, and Path.rename keeps the inode number, because a rename changes only the directory entry. os.link adds a second name, Path.samefile compares the device and the inode, and st_nlink counts the names. os.statvfs describes the file system that holds a path, and f_bavail times f_frsize is the free space for a normal user.
#include <filesystem>
#include <fstream>
#include <iostream>
#include <set>

namespace fs = std::filesystem;

int main() {
    fs::create_directories("tree/src");
    std::ofstream("tree/src/main.txt") << "main\n";
    std::ofstream("tree/readme.txt") << "read me\n";

    // recursive_directory_iterator walks the tree; the order is not fixed, so use a set.
    std::set<std::string> names;
    for (const auto &e : fs::recursive_directory_iterator("tree")) {
        names.insert(e.path().generic_string() + (e.is_directory() ? "/" : ""));
    }
    for (const auto &n : names) std::cout << n << '\n';

    // equivalent compares the files that two paths name.
    fs::create_hard_link("tree/src/main.txt", "tree/main-link.txt");
    std::cout << std::boolalpha;
    std::cout << "equivalent: " << fs::equivalent("tree/src/main.txt", "tree/main-link.txt") << '\n';
    std::cout << "links: " << fs::hard_link_count("tree/src/main.txt") << '\n';

    // space describes the file system that holds a path.
    fs::space_info s = fs::space("tree");
    std::cout << "available <= capacity: " << (s.available <= s.capacity) << '\n';

    // The overload with std::error_code reports an error without an exception.
    std::error_code ec;
    fs::file_size("tree/missing.txt", ec);
    std::cout << "missing: " << (ec == std::errc::no_such_file_or_directory) << '\n';
}
Output
tree/readme.txt
tree/src/
tree/src/main.txt
equivalent: true
links: 2
available <= capacity: true
missing: true
  • Verdict: stdlib. std::filesystem has the operations of POSIX in a portable form. recursive_directory_iterator walks the tree in no fixed order, so the program puts the names in a std::set. equivalent compares the files that two paths name, hard_link_count counts the names, and space describes the file system. Each call has an overload with std::error_code that does not throw.
JavaGitHub
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

public class Main {
  public static void main(String[] args) throws IOException {
    Path dir = Files.createDirectories(Path.of("tree", "src"));
    Path main = Files.writeString(dir.resolve("main.txt"), "main\n");

    // A hard link is a second name. isSameFile compares the files, not the names.
    Path link = Files.createLink(Path.of("tree", "main-link.txt"), main);
    System.out.println("same file: " + Files.isSameFile(main, link));
    // The "unix" attribute view gives the inode number and the link count.
    System.out.println("links: " + Files.getAttribute(main, "unix:nlink"));

    // A FileStore is the storage that holds a path.
    FileStore store = Files.getFileStore(main);
    System.out.println("usable space > 0: " + (store.getUsableSpace() > 0));
    System.out.println("separator: " + FileSystems.getDefault().getSeparator());

    // A zip file is a file system too. The same Path and Files calls work in it.
    URI zip = URI.create("jar:" + Path.of("tree.zip").toAbsolutePath().toUri());
    try (FileSystem zfs = FileSystems.newFileSystem(zip, Map.of("create", "true"))) {
      Path inZip = zfs.getPath("/docs/notes.txt");
      Files.createDirectories(inZip.getParent());
      Files.writeString(inZip, "inside a zip\n");
      System.out.print("read back: " + Files.readString(inZip));
      System.out.println("zip separator: " + zfs.getSeparator());
    }
    System.out.println("zip exists: " + Files.isRegularFile(Path.of("tree.zip")));
  }
}
Output
same file: true
links: 2
usable space > 0: true
separator: /
read back: inside a zip
zip separator: /
zip exists: true
  • Verdict: stdlib. Files.isSameFile tells whether two paths name the same file, and the unix attribute view gives the link count. Files.getFileStore gives the storage that holds a path. A zip archive is also a FileSystem: FileSystems.newFileSystem opens it, and the same Files.writeString and Files.readString calls work inside it.
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <unistd.h>

static void put(const char *path, const char *text) {
    FILE *f = fopen(path, "w");
    fputs(text, f);
    fclose(f);
}

int main(void) {
    mkdir("tree", 0755);
    put("tree/readme.txt", "read me\n");

    // stat fills a struct stat: the type is in st_mode, the identity in st_dev and st_ino.
    struct stat a, b;
    stat("tree", &a);
    printf("tree is a directory: %d\n", S_ISDIR(a.st_mode));
    stat("tree/readme.txt", &a);
    printf("readme.txt is a regular file: %d, size %lld\n", S_ISREG(a.st_mode), (long long)a.st_size);

    // rename changes the name in the directory; the inode stays.
    rename("tree/readme.txt", "tree/README.txt");
    stat("tree/README.txt", &b);
    printf("same inode after rename: %d\n", a.st_ino == b.st_ino);

    // link adds a second name; st_nlink counts the names.
    link("tree/README.txt", "tree/link.txt");
    stat("tree/link.txt", &b);
    printf("same file: %d, links %ld\n", a.st_dev == b.st_dev && a.st_ino == b.st_ino, (long)b.st_nlink);

    // statvfs describes the file system that holds a path.
    struct statvfs v;
    if (statvfs("tree", &v) == 0) {
        printf("free bytes for this user > 0: %d\n", (unsigned long long)v.f_bavail * v.f_frsize > 0);
    }

    // A missing file gives -1 and errno ENOENT.
    if (stat("tree/missing.txt", &a) == -1) {
        printf("missing: %s\n", errno == ENOENT ? "ENOENT" : strerror(errno));
    }
    return 0;
}
Output
tree is a directory: 1
readme.txt is a regular file: 1, size 8
same inode after rename: 1
same file: 1, links 2
free bytes for this user > 0: 1
missing: ENOENT
  • Verdict: library. ISO C has fopen, remove and rename, but no directories and no file attributes. The program uses POSIX: mkdir, stat with S_ISDIR and S_ISREG, link, and statvfs. A rename keeps st_ino, a link raises st_nlink to 2, and a missing name gives -1 with errno set to ENOENT.
using System.IO;

Directory.CreateDirectory("tree/src");
File.WriteAllText("tree/src/main.txt", "main\n");
File.WriteAllText("tree/readme.txt", "read me\n");

// DirectoryInfo lists FileSystemInfo objects: DirectoryInfo or FileInfo.
foreach (var e in new DirectoryInfo("tree").EnumerateFileSystemInfos().OrderBy(e => e.Name, StringComparer.Ordinal))
{
    Console.WriteLine($"{e.Name} {(e is DirectoryInfo ? "dir" : "file")}");
}

// File.Move with the same directory is a rename; the content stays.
File.Move("tree/readme.txt", "tree/README.txt");
Console.WriteLine($"size after move: {new FileInfo("tree/README.txt").Length}");

// A symbolic link is a file that holds a path. .NET 10 has no method that makes a hard link.
File.CreateSymbolicLink("tree/main-link.txt", "src/main.txt");
var link = new FileInfo("tree/main-link.txt");
Console.WriteLine($"link target: {link.LinkTarget}");
Console.WriteLine($"is reparse point: {link.Attributes.HasFlag(FileAttributes.ReparsePoint)}");

// DriveInfo describes the volumes. On Unix the root directory is one of them.
var root = DriveInfo.GetDrives().FirstOrDefault(d => d.Name == "/");
Console.WriteLine($"root volume ready: {root?.IsReady}");
Console.WriteLine($"separator: {Path.DirectorySeparatorChar}");

try
{
    File.ReadAllText("tree/missing.txt");
}
catch (FileNotFoundException e)
{
    Console.WriteLine($"missing: {e.GetType().Name}");
}
Output
readme.txt file
src dir
size after move: 8
link target: src/main.txt
is reparse point: True
root volume ready: True
separator: /
missing: FileNotFoundException
  • Verdict: stdlib. DirectoryInfo.EnumerateFileSystemInfos gives a DirectoryInfo or a FileInfo for each entry. File.Move in one directory is a rename. File.CreateSymbolicLink makes a symbolic link, and LinkTarget reads its path, but .NET 10 has no method that makes a hard link. DriveInfo.GetDrives lists the volumes, and on Unix the root directory / is one of them.
JavaScriptGitHub
const fs = require("node:fs");

fs.mkdirSync("tree/src", { recursive: true });
fs.writeFileSync("tree/src/main.txt", "main\n");
fs.writeFileSync("tree/readme.txt", "read me\n");

// readdir with withFileTypes gives a Dirent with the type of each entry.
for (const e of fs.readdirSync("tree", { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
  console.log(e.name, e.isDirectory() ? "dir" : "file");
}

// stat gives the device ID, the inode number and the link count.
const before = fs.statSync("tree/readme.txt").ino;
fs.renameSync("tree/readme.txt", "tree/README.txt");
console.log("same inode after rename:", fs.statSync("tree/README.txt").ino === before);

fs.linkSync("tree/src/main.txt", "tree/main-link.txt");
const a = fs.statSync("tree/src/main.txt");
const b = fs.statSync("tree/main-link.txt");
console.log("same file:", a.dev === b.dev && a.ino === b.ino);
console.log("links:", a.nlink);

// statfs describes the file system that holds the path.
const s = fs.statfsSync("tree");
console.log("block size > 0:", s.bsize > 0);
console.log("free bytes for this user > 0:", s.bavail * s.bsize > 0);
Output
readme.txt file
src dir
same inode after rename: true
same file: true
links: 2
block size > 0: true
free bytes for this user > 0: true
  • Verdict: stdlib. Node.js fs.readdirSync with withFileTypes gives Dirent objects with the type of each entry. fs.statSync gives dev, ino and nlink, so the program sees that a rename keeps the inode and that a link is the same file. fs.statfsSync describes the file system, as statvfs does in C.
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"testing/fstest"
)

// count works on any fs.FS: a directory on the disk or a tree in memory.
func count(fsys fs.FS) (files, dirs int) {
	fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if d.IsDir() {
			dirs++
		} else {
			files++
		}
		return nil
	})
	return files, dirs
}

func main() {
	os.MkdirAll("tree/src", 0o755)
	os.WriteFile("tree/src/main.txt", []byte("main\n"), 0o644)
	os.WriteFile("tree/readme.txt", []byte("read me\n"), 0o644)

	// os.DirFS gives the directory tree as an fs.FS.
	f, d := count(os.DirFS("tree"))
	fmt.Println("disk:", f, "files,", d, "directories")

	// fstest.MapFS is a file system in memory with the same interface.
	mem := fstest.MapFS{
		"a.txt":     {Data: []byte("a")},
		"sub/b.txt": {Data: []byte("b")},
		"sub/c.txt": {Data: []byte("c")},
	}
	f, d = count(mem)
	fmt.Println("memory:", f, "files,", d, "directories")

	// os.SameFile compares the device and the inode of two names.
	os.Link("tree/src/main.txt", "tree/main-link.txt")
	a, _ := os.Stat("tree/src/main.txt")
	b, _ := os.Stat("tree/main-link.txt")
	fmt.Println("same file:", os.SameFile(a, b))

	// A missing name gives an error that matches fs.ErrNotExist.
	_, err := os.Stat("tree/missing.txt")
	fmt.Println("not exist:", errors.Is(err, fs.ErrNotExist))
}
Output
disk: 2 files, 2 directories
memory: 3 files, 2 directories
same file: true
not exist: true
  • Verdict: stdlib. The io/fs interfaces separate the code from the storage. os.DirFS gives a directory on the disk as an fs.FS, and fstest.MapFS is a tree in memory, so one function with fs.WalkDir counts both. os.SameFile compares two FileInfo values, and a missing file gives an error that matches fs.ErrNotExist.
RustGitHub
use std::fs;
use std::os::unix::fs::MetadataExt;

fn main() -> std::io::Result<()> {
    fs::create_dir_all("tree/src")?;
    fs::write("tree/src/main.txt", "main\n")?;
    fs::write("tree/readme.txt", "read me\n")?;

    // read_dir gives the entries of a directory in no fixed order, so sort them.
    let mut names: Vec<(String, bool)> = fs::read_dir("tree")?
        .map(|e| e.map(|e| (e.file_name().to_string_lossy().into_owned(), e.path().is_dir())))
        .collect::<Result<_, _>>()?;
    names.sort();
    for (name, is_dir) in &names {
        println!("{name} {}", if *is_dir { "dir" } else { "file" });
    }

    // MetadataExt (Unix only) gives the device ID, the inode number and the link count.
    let before = fs::metadata("tree/readme.txt")?.ino();
    fs::rename("tree/readme.txt", "tree/README.txt")?;
    println!("same inode after rename: {}", fs::metadata("tree/README.txt")?.ino() == before);

    fs::hard_link("tree/src/main.txt", "tree/main-link.txt")?;
    let a = fs::metadata("tree/src/main.txt")?;
    let b = fs::metadata("tree/main-link.txt")?;
    println!("same file: {}", a.dev() == b.dev() && a.ino() == b.ino());
    println!("links: {}", a.nlink());

    // An error has a kind, so the program can test for a missing file.
    let err = fs::metadata("tree/missing.txt").unwrap_err();
    println!("missing: {:?}", err.kind());
    Ok(())
}
Output
readme.txt file
src dir
same inode after rename: true
same file: true
links: 2
missing: NotFound
  • Verdict: stdlib. fs::read_dir gives the entries in no fixed order, so the program sorts them. The Unix extension trait MetadataExt gives dev, ino and nlink, and they show that fs::rename keeps the inode and that fs::hard_link adds a name to the same file. An error has an ErrorKind, such as NotFound.
  • Hard links and symbolic links. A hard link is one more directory entry for the same file. A symbolic link is a small file that holds a path. See the page about links.
  • Virtual file systems. Some file systems have no disk behind them. A virtual file system gives files that are "computed on request", for example the files of procfs and sysfs6, and procfs "exposes process information as special files"6. A zip archive, a tree in memory and the files built into a program can also be file systems in a library, as in Java and Go.
  • Network file systems. With a network file system, "Programs using local interfaces can transparently create, manage and access hierarchical directories and files in remote network-connected computers"6. NFS and SMB are examples6. POSIX includes "parts of the tree that may be remotely mounted from other machines on the network"4 in the rule for st_ino and st_dev.
  • Databases. A database also keeps data on a disk, but it gives records and queries instead of byte streams and names.

Pitfalls

  • Case rules differ. Microsoft says: "Do not assume case sensitivity"13. Windows treats OSCAR, Oscar and oscar as the same name by default, but "some file systems (such as a POSIX-compliant file system) may consider them as different"13. Code that works on one system can overwrite a file, or not find it, on the other.
  • Directory order is not defined. Python returns the entries of listdir "in arbitrary order"14. In Rust, "The order in which read_dir returns entries can change between calls"15. Sort the names when the order matters, for example in tests and in build outputs.
  • A rename does not cross file systems. POSIX rename fails with EXDEV when the two names are "on different file systems and the implementation does not support hard links between file systems"16. A move to another mount point must copy the data and then remove the old file.
  • An inode number alone is not an identity. Two files on two file systems can have the same inode number. Compare the device ID and the inode number together. Python warns that on Windows, the st_ino, st_dev and st_nlink of a cached DirEntry.stat() result "are always set to zero"14, so call os.stat() for them.
  • Free space has two numbers. statvfs gives f_bfree, the "Number of free blocks", and f_bavail, the "Number of free blocks for unprivileged users"14. A normal program can use only the second number.
  • The block unit is not fixed. The unit of st_blocks "is not defined within POSIX.1-2024", and "In some implementations it is 512 bytes"4. Do not use st_blocks as a size in bytes without a check.

Cost

Each call to the file system of the operating system is a system call, which costs much more than a call to a function in the program. The name lookup is done one component at a time, so a long path needs a lookup in each directory. A program that lists a directory and then calls stat on each name makes one more system call per file. Python's documentation says that scandir "can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory"14. On a network file system, each call can also wait for the network.

History

Daley and Neumann described the file system of Multics in 1965. They wrote that for on-line work, "user owned off-line detachable storage media such as cards and tape become highly undesirable"17. In it, "The file structure consists of a basic tree hierarchy of files, across which links may be added to facilitate simple access to files elsewhere in the hierarchy"17. Wikipedia says that "The first file system to support arbitrary hierarchies of directories was used in the Multics operating system"6.

Unix took the tree and made it simpler. The paper of Ritchie and Thompson (1974) lists "A hierarchical file system incorporating demountable volumes" as the first feature of the system3. It describes the i-number, the i-node and the mount of a volume on a directory3, and these ideas are still in POSIX. Windows keeps a separate root for each volume, and the file systems of MS-DOS, Windows and the Apple systems also have directory trees6.

References

  1. The Open Group, POSIX.1-2024, Base Definitions, Chapter 3, Definitions, 3.103 Directory, 3.104 Directory Entry (or Hard Link), 3.139 File, 3.152 File Serial Number, 3.153 File System, 3.210 Mount Point, 3.310 Regular File
  2. The Open Group, POSIX.1-2024, Base Definitions, Chapter 4, General Concepts, 4.16 Pathname Resolution
  3. D. M. Ritchie and K. Thompson, The UNIX Time-Sharing System (1974, the BSTJ version), Abstract; 3.4 Removable file systems; IV. Implementation of the file system
  4. The Open Group, POSIX.1-2024, sys/stat.h, Application Usage
  5. File Systems, Win32 apps, Microsoft Learn, Volume Management
  6. File system, Wikipedia, Directories; Types of file systems
  7. Java SE 25 API, java.nio.file.FileSystem, class description
  8. Java SE 25 API, java.nio.file.FileStore, class description
  9. Go standard library, package io/fs, Overview
  10. GNU Bash Reference Manual, 6.4 Bash Conditional Expressions
  11. about_FileSystem_Provider, PowerShell 7.6, Microsoft Learn, Detailed description
  12. Filesystem library, C++ reference, cppreference.com, introduction
  13. Naming Files, Paths, and Namespaces, Win32 apps, Microsoft Learn, Naming Conventions
  14. The Python Standard Library, os, listdir, scandir, DirEntry.stat, statvfs_result
  15. The Rust Standard Library, std::fs::read_dir, Platform-specific behavior
  16. The Open Group, POSIX.1-2024, rename, Errors, EXDEV
  17. R. C. Daley and P. G. Neumann, A General-Purpose File System For Secondary Storage (FJCC 1965), 2. The File Structure and Access Control

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/N9ZE82/text.yaml