Logo  

CS471/571 - Operating Systems

Displaying exercises/e3/solution/cp.c

#include "types.h"
#include "stat.h"
#include "user.h"
#include "fcntl.h"

int main(int argc, char *argv[])
{
  char buf[512];
  int src, dst, n;

  if(argc < 3){
    printf(1, "Usage: cp <src> <dst>\n");
    exit();
  }

  if((src = open(argv[1], O_RDONLY)) < 0){
    printf(1, "cp: cannot open source %s\n", argv[1]);
    exit();
  }
  if((dst = open(argv[2], O_WRONLY | O_CREATE)) < 0){
    printf(1, "cp: cannot open destination %s\n", argv[2]);
    exit();
  }

  while((n = read(src, buf, sizeof(buf))) > 0) {
    if (write(dst, buf, n) != n) {
      printf(1, "cp: write error\n");
      exit();
    }
  }
  if(n < 0){
    printf(1, "cp: read error\n");
    exit();
  }

  close(src);
  close(dst);

  exit();
}