CS360: Exam 1: 10/22/97. Question 4 (16 points)


Part 1

Explain what the following piece of code does. In your explanation, make sure you detail what the format of the input file is.
#include < fcntl.h >
#include "rb.h"

main()
{
  int fd;
  Rb_node names, tmp;
  int i;
  char *name;
  char *ssn;

  names = make_rb();
  fd = open("inputfile", O_RDONLY);
  if (fd < 0) { perror("inputfile"); exit(1); }

  while (read(fd, &i, sizeof(int)) == sizeof(int)) {
    name = (char *) malloc(sizeof(char)*(i+1));
    read(fd, name, i);
    name[i] = '\0';
    ssn = (char *) malloc(sizeof(char)*(12)); /* XXX-XX-XXXX */
    read(fd, ssn, 11);
    ssn[11] = '\0';
    rb_insert(names, name, ssn);
  }

  rb_traverse(tmp, names) {
    printf("%s %s\n", tmp->v.val, tmp->k.key);
  }
} 

Part 2

The above code is inefficient. Explain why, and rewrite it so that it is efficient. You may use any of the system or library calls in the cheat sheet.