Search⌘ K

Reading and Writing Files

Explore how programs read and write files in UNIX by examining system calls such as open, read, write, and close. Understand how standard file descriptors work and how to trace these operations using strace. Gain insights into the underlying file descriptor table and file handling mechanics within operating systems.

We'll cover the following...

Once we have some files, of course, we might like to read or write them. Let’s start by reading an existing file. If we were typing at a command line, we might just use the program cat to dump the contents of the file to the screen.

Shell
prompt> echo hello > foo
prompt> cat foo
hello
prompt>

Try it out yourself:

Terminal 1
Terminal
Loading...

In this code snippet, we redirect the output of the program echo to the file foo, which then contains the word “hello” in it. We then use cat to see the contents of the file. But how does the cat program access the file foo?

Strace to trace cat

To find this out, we’ll use an incredibly useful tool to trace the system calls made by a program. On Linux, the tool is called strace; other systems have similar tools (see dtruss on a Mac, or truss on some older UNIX variants). What strace does is trace every system call made by a program while it runs, and dump the trace to the screen for you to see.

TIP: USE STRACE (AND SIMILAR TOOLS)

The strace tool provides an ...