CSE271 Lab 9: Files and Directories (ls and touch)
Announcements
- Next Friday is Exam #2. Topics include:
- Coding style
- Debugging tools and techniques
- Bash scripting
- UNIX programming
- ... bring questions to Monday's class!
- Homework #5 is due Saturday.
Collaborative Programming
- Recently a few students participated in helping to
write versions of cp and who.
- We will continue that today, by writing touch, and
implementing
the simple ls that we discussed Monday.
- Please feel free to work and discuss today's labwork in teams (of
any number of students)
touch
- What is touch(1)? What does it do?
- How does it work?
- Task 1: implement touch(1)
Writing ls
Task 2: Now that touch is complete, let's revisit ls and
implement a simple version. You might review the notes from Monday, but in the end, we want to implement something like:
main()
opendir()
while ( readdir() )
print d_name
closedir()
return 0
This version would only print out the names of files (e.g., as ls does, and not anything further).
Extending ls
Task 3: Now we can extend ls
to work like ls -l works.
A (working) version of ls is
here (in case you
have questions about task 2).
This lab will help walk you through the necessary
steps to extend it.
Our goal, at the end, is to have an equivalent to ls -l.
How do we add -l to our ls?
- Q: What does -l display?
- A: modtime, size, owner, group, links, type, permissions
- Q: Where can we learn about these?
- A: As always, search the manual
- Result: the stat() system call
How does stat() work?
- int stat(char *name, struct stat *buf)
- struct contains
- st_mode
- st_uid
- st_gid
- st_size
- st_nlink
- st_mtime
- So we can modify ls to provide -l features using stat() on the filename
How well should your ls -l work?
- Perfectly for filenames, filesizes, but we can fix the rest.
- We can use ctime() to convert the mod time.
- Owner and group info are stored as numbers, so we need to map them to
names (shortly below).
- What about type? permissions?
Where are type and permissions stored?
- st_mode is a 16 bit value. Within it, we have
- four bits for the file type, followed by
- three bits for suid, sgid, and sticky bit, followed by
- nine bits for owner, group and world rwx permissions
- So we will use subfield coding.
- Much like telephone numbers, IP addresses, etc.
Bits and subfields
UIDs and GIDs
- UIDs and GIDs from stat() are just numbers
- How can we convert them to names?
- Then we can finish our ls -l
- First, search manual pages
Converting UIDs
- From the man pages, we learn about /etc/passwd and ypcat
passwd
- The getpwuid() function provides access to user information.
- A similar function is available to convert gid information.
- Your ls should now be able to generate correct permissions,
types, owner, group, etc., just like ls -l
Last revised: 18 March 2009, Prof. Davison.