Operating System - File Operations in Operating Systems
Files are a fundamental part of any operating system. The OS provides various file operations to create, manage, and manipulate files. These operations allow users and programs to interact with files effectively.
1. Create
-
Used to make a new empty file in the file system.
-
The OS allocates space and updates the directory structure.
-
Example:
touch file.txt
in Linux or creating a new Word document.
2. Open
-
A file must be opened before it can be read or written.
-
The OS checks permissions, loads metadata into memory, and returns a file handle or descriptor.
-
Example:
fopen("data.txt", "r")
in C.
3. Read
-
Retrieves data from a file into memory.
-
The file pointer indicates the current read position and moves as data is read.
-
Example: Reading lines from a log file.
4. Write
-
Stores data into a file at the current file pointer location.
-
If the file does not exist, it may be created. If it does, data can be appended or overwritten.
-
Example: Writing user input into a file.
5. Seek (Reposition Pointer)
-
Moves the file pointer to a specific location for reading or writing.
-
Enables random access in files.
-
Example: Skipping to the middle of a file to update a record.
6. Close
-
Closes an open file and frees system resources (memory, file descriptors).
-
Data in buffers is written to the disk if not already saved.
-
Example:
fclose(file)
in C.
7. Delete
-
Removes a file from the file system.
-
The OS deallocates space and updates the directory structure.
-
Example:
rm file.txt
in Linux or sending a file to the recycle bin.
8. Rename
-
Changes the name of a file.
-
It does not affect the contents or location of the file.
-
Example:
mv old.txt new.txt
in Linux.
9. Truncate
-
Removes all or part of a file’s data but keeps the file itself.
-
Often used to reset file contents without deleting the file.
-
Example: Truncating a log file to save disk space.
These file operations are essential for interacting with files at both the user level (via applications) and the system level (via the OS). Understanding them is key to working efficiently with any file system.