Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Question 1: argc

Consider the following simple C program:

simple.c

int
main(int argc, char *argv[])
{
    printf("argc = %d\n");
}

If we compile and run this program like this:

$ simple 1 2 3

What is the output?

Question 2: cat.c

Consider the original implementation of cat.c found in xv6 shown below. Modify this version of cat to accept a command line option -m cols that will truncate each line to cols columns. That is cols is the maximum line length. Make neat code changes/additions and explain your solution.

cat.c

#include "kernel/types.h"
#include "kernel/fcntl.h"
#include "user/user.h"

char buf[512];

void
cat(int fd)
{
  int n;

  while((n = read(fd, buf, sizeof(buf))) > 0) {
    if (write(1, buf, n) != n) {
      fprintf(2, "cat: write error\n");
      exit(1);
    }
  }
  if(n < 0){
    fprintf(2, "cat: read error\n");
    exit(1);
  }
}

int
main(int argc, char *argv[])
{
  int fd, i;

  if(argc <= 1){
    cat(0);
    exit(0);
  }

  for(i = 1; i < argc; i++){
    if((fd = open(argv[i], O_RDONLY)) < 0){
      fprintf(2, "cat: cannot open %s\n", argv[i]);
      exit(1);
    }
    cat(fd);
    close(fd);
  }
  exit(0);
}

Question 3: buggy

What is a problem with this code? Assume foo.txt looks like this:

foo.txt

$ cat foo.txt
This-is-a-test-file.

bad.c

int
main(int argc, char *argv[])
{
  int fd, n;
  char buf[128];

  fd = open("foo.txt", O_RDONLY);
  if (fd < 0)
    exit(-1);
  n = read(fd, buf, 10);
  printf("buf = %s\n", buf);
  close(fd);
}

Question 4: wc

Explain what the following code snippet from the wc command does:

if(strchr(" \r\t\n\v", buf[i]))
  inword = 0;
else if(!inword){
  w++;
  inword = 1;
}

Question 5: simdiff.c

Write a program called simdiff.c that just determines if two files are the same or not. It works like this:

$ simdiff foo.txt bar.txt
SAME
$ simdiff foo.txt baz.txt
DIFFERENT

Note that two files are different if any corresponding characters in both files are different or if the files are different sizes.