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)
👉 Steps:
-
Write new data to a temporary file
-
Force it to disk using
fsync() -
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
Internally:
Getting File Status (Metadata)
📌 System Calls:
-
stat(pathname) -
fstat(fd)
📊 Purpose:
Retrieve metadata about a file
📦 Important Metadata Fields
| Field | Meaning |
|---|---|
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
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:
🔷 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
Post a Comment