Operating System Lab (CS33201) –
Assignment 1 Solutions
1. Study of Unix/Linux General Purpose Commands
Command | Description | Example
--------- | -------------------------------- | -------------------------
man | Help manual | man ls
who | Who is logged in | who
cat | Display file content | cat file.txt
cd | Change directory | cd /home/user
cp | Copy files/directories | cp a.txt b.txt
ps | Process status | ps aux
ls | List files | ls -l
mv | Move/Rename file | mv old.txt new.txt
rm | Remove file | rm file.txt
mkdir | Make directory | mkdir folder
rmdir | Remove empty directory | rmdir folder
echo | Print to terminal | echo Hello
more | View file page-wise | more file.txt
date | Show date/time | date
time | Measure execution time | time ./a.out
kill | Terminate process | kill -9 PID
history | Show command history | history
chmod | Change permissions | chmod 755 file.sh
chown | Change file owner | chown user file.txt
pwd | Print working directory | pwd
cal | Display calendar | cal
logout | Logout of shell | logout
shutdown | Shut down system | shutdown now
2. Simulate `ls` in C
#include <stdio.h>
#include <dirent.h>
int main() {
struct dirent *de;
DIR *dr = opendir(".");
if (dr == NULL) return 0;
while ((de = readdir(dr)) != NULL)
printf("%s\n", de->d_name);
closedir(dr);
return 0;
3. File Operations in C
Create/Write:
int fd = open("file.txt", O_CREAT | O_WRONLY, 0644);
write(fd, "Hello OS Lab", 12);
close(fd);
Read:
char buffer[100];
int fd = open("file.txt", O_RDONLY);
read(fd, buffer, 100);
printf("Content: %s\n", buffer);
close(fd);
Copy File:
int src = open("file.txt", O_RDONLY);
int dest = open("copy.txt", O_CREAT | O_WRONLY, 0644);
char buffer[1024]; int n;
while ((n = read(src, buffer, 1024)) > 0)
write(dest, buffer, n);
close(src); close(dest);
Reverse Read:
off_t size = lseek(fd, 0, SEEK_END);
for (off_t i = 1; i <= size; i++) {
lseek(fd, -i, SEEK_END);
read(fd, &ch, 1); write(1, &ch, 1);
4. lseek() vs stat()
off_t size = lseek(fd, 0, SEEK_END);
stat("file.txt", &st);
printf("Size using lseek: %ld\n", size);
printf("Size using stat: %ld\n", st.st_size);
5. Directory + Inode info
chdir("/your/target/path");
getcwd(cwd, sizeof(cwd));
DIR *d = opendir(".");
while ((dir = readdir(d)) != NULL) {
stat(dir->d_name, &st);
printf("File: %s, Inode: %ld\n", dir->d_name, st.st_ino);
closedir(d);