Directory Operations in Operating Systems

 

Directory Operations in Operating Systems

Directories are special structures used to organize files. Unlike regular files, you cannot directly write to directories because they store file system metadata.

👉 Instead, directories are modified indirectly through system calls.


1. Creating Directories

 System Call: mkdir()

  • Used to create a new directory

  • Syntax:

    mkdir("dirname", permissions);

 Example

mkdir foo

Internally:

mkdir("foo", 0777);

What Happens When a Directory is Created?

Even an “empty” directory contains:

EntryMeaning
.        Refers to itself
..        Refers to parent directory

👉 These ensure:

  • Navigation in file system

  • Hierarchical structure


2. Reading Directories

Directories cannot be read using normal read() calls. Instead, special APIs are used.

 System Calls:

  • opendir()

  • readdir()

  • closedir()


Basic Workflow

DIR *dp = opendir("."); struct dirent *d; while ((d = readdir(dp)) != NULL) { printf("%d %s\n", d->d_ino, d->d_name); } closedir(dp);

Directory Entry Structure

struct dirent { char d_name[256]; // filename ino_t d_ino; // inode number off_t d_off; // offset unsigned short d_reclen; unsigned char d_type; };

Key Idea

👉 Directory only stores:

  • Filename

  • Inode number

For more details (size, permissions), use:

  • stat() system call


 Real-world Example

Command:

ls
  • Uses readdir() internally

  • ls -l additionally uses stat() for metadata


3. Deleting Directories

 System Call: rmdir()

  • Used to remove a directory

  • Condition: Directory must be empty


 Example

rmdir foo

 Important Constraint

👉 Directory must contain only:

  • .

  • ..

Otherwise:

  • rmdir() fails


 Why Restriction Exists?

  • Prevents accidental deletion of large data

  • Safer than file deletion


Important Warning (Real System Behavior)

Command:

rm -rf *

👉 Recursively deletes:

  • All files

  • All directories

⚠️ If run at root (/):

  • Entire system data can be erased


 Summary Table

OperationSystem CallKey Idea
Create directory    mkdir()    Creates with . and ..
Read directory    opendir(), readdir()    Iterates entries
Delete directory    rmdir()    Only if empty

Key Concept for Students

👉 Directories are not normal files:

  • Cannot be directly modified

  • Managed only via OS-controlled operations

👉 They act as:

filename → inode mapping

Comments

Popular posts from this blog

Operating Systems OS PCCST403 Semester 4 BTech KTU CS 2024 Scheme

Introduction to Operating System -Virtualization, Concurrency, and Persistence

Operating Systems PCCST403 Scheme and Syllabus