A simple implementation of the “tee” command

Published by moxlotus on

Recently, I have started to read the book "The Linux Programming Interface". In chapter 4 of the book, the reader is given the exercise to create the tee command. For those of you who is not familiar what a tee command does, it is a simple command that reads the input from stdin and write it to a file as well as the stdout. So with that in mind, below is my solution to the exercise.

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "./tlpi-dist/lib/tlpi_hdr.h" // You may download this header file from book author's website

#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif

int main(int argc, char *argv[]){
  int flags, output_fd;
  ssize_t num_read;
  char buffer[BUF_SIZE];
  char *file_name;
  if (argc > 3 || strcmp(argv[1], "--help") == 0)
    usageErr("%s [-a] filename\n", argv[0]);

  if(strcmp(argv[1], "-a") == 0) {
    flags = O_CREAT | O_APPEND | O_WRONLY;
    file_name = argv[2];
  } else {
    flags = O_CREAT | O_TRUNC | O_WRONLY;
    file_name = argv[1];
  }

  mode_t file_perm = S_IRUSR | S_IWUSR | S_IXUSR | 
                     S_IRGRP | S_IWGRP | S_IXGRP |
                     S_IROTH | S_IWOTH | S_IXOTH; // file permission 777

  output_fd = open(file_name, flags, file_perm);
  if (output_fd == -1)
    errExit("opening file %s", argv[1]);

  while((num_read = read(0, buffer, BUF_SIZE)) > 0){
    if(write(1, buffer, num_read) != num_read)
      fatal("couldn't write whole buffer stdou");
    if(write(output_fd, buffer, num_read) != num_read)
      fatal("couldn't write whole buffer to %s", output_fd);
  }

  if(num_read == -1)
    errExit("read");

  if (close(output_fd) == -1)
    errExit("close file %s", argv[1]);

  exit(EXIT_SUCCESS);
}
Share it with others
Categories: Linux