Renaming and Removing Files in OS

 

Renaming Files in OS

📌 System Call: rename(old, new)

  • Used to change the name of a file

  • Takes:

    • old → current file name

    • new → new file name

🔑 Key Concept: Atomic Operation

  • The rename operation is atomic:

    • After a crash → file is either:

      • completely renamed, OR

      • still has the old name

    • ❌ No partial or inconsistent state

💡 Why is this important?

It enables safe file updates, especially in applications like editors or databases.

📖 Example Workflow (Safe Update)

open("foo.txt.tmp") write(new data) fsync(fd) close(fd) rename("foo.txt.tmp", "foo.txt")

👉 Steps:

  1. Write new data to a temporary file

  2. Force it to disk using fsync()

  3. Atomically replace the old file using rename()

✔ Ensures:

  • No data corruption

  • Crash-safe updates


Removing Files in OS

📌 System Call: unlink(filename)

  • Used to delete a file

  • Removes the file name from directory

⚠️ Important Insight

👉 unlink() does NOT immediately erase file data

Instead:

  • Removes the directory entry

  • Actual data is deleted only when no references remain

🔑 Why called “unlink”?

Because it:

  • Unlinks the filename from its inode

  • The file disappears from the directory

📖 Example

rm foo

Internally:

unlink("foo");

Getting File Status (Metadata)

📌 System Calls:

  • stat(pathname)

  • fstat(fd)

📊 Purpose:

Retrieve metadata about a file


📦 Important Metadata Fields

FieldMeaning
st_ino    Inode number (unique file ID)
st_size    File size (bytes)
st_mode    Permissions
st_uid, st_gid    Owner and group
st_nlink    Number of links
st_atime    Last access time
st_mtime    Last modification time
st_ctime    Metadata change time

💡 Example Command

stat file

Output shows:

  • Size

  • Permissions

  • Owner

  • Timestamps

  • Inode number


🔷 Key Concept: Inode

  • Each file is represented internally by an inode

  • Stores:

    • Metadata

    • Disk block locations

  • Directory maps:

    filename → inode number

🔷 Summary 

  • rename()

    • Atomic file renaming

    • Used for safe updates

  • unlink()

    • Removes file name (not immediate data deletion)

    • Deletes file when no references remain

  • stat() / fstat()

    • Retrieves file metadata

    • Uses inode structure internally


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