Curiosity and the I/O Cat

Create your GitHub repo for this lab here: classroom.github.com/a/2TT8LvU_

In this lab, we’ll learn a bit more about I/O by building our own version of the cat Unix utility. You can learn more about cat by checking the man pages with man cat.

Thus far, we’ve only really covered output – printing to the terminal with printf or puts. To implement cat, we also need to be able to read a file and then print its contents. The functions you should use for this lab are:

You’ll want to review the man pages for each of these to understand how they work.

Check out the class schedule page for a full walkthrough of cat to get an idea of how it should work. The basic workflow is:

  1. Loop through each command line argument
  2. Each argument is a file, so open it
  3. If opening the file was successful, read its contents line by line
  4. Print each of the lines to the terminal
  5. Close the file
  6. Move on to the next file

That’s it!

When you read the files, you have to have somewhere to put their contents temporarily before printing them – a buffer. We’ll create a character array to serve as our buffer:

// Create a buffer of 128 characters
char buf[128];

// ... and then pass 'buf' to the fgets function

Testing your code

When you are done, your cat program should be able to concatenate several files. If no file is specified, or the file name is ‘-’, it should read from stdin just like cat does. Test it out with a few text files of varying sizes, and compare your output with that of the regular cat utility.

Here are some test cases to verify that everything is working properly.

[mmalensek@mmalensek-vm ~]$ ./sfcat
Type something
Type something (whatever you type gets repeated!)
[mmalensek@mmalensek-vm ~]$ echo Hello | ./sfcat
Hello
[mmalensek@mmalensek-vm ~]$ ./sfcat README.md
(contents of README.md are displayed)
[mmalensek@mmalensek-vm ~]$ echo Wow | ./sfcat README.md - sfcat.c
(contents of README.md are displayed, then "Wow", then contents of sfcat.c)

When you are finished, check your code into your GitHub repository to submit.

Bonus round: if you are already done and need an additional challenge, use getopt() to parse command line options and support a -m flag that turns on an option that adds “meow!” to the end of each line. Now that’s an exciting feature!