/* This program demonstrates the use of open(), close(), read() and write()
 * to copy the contents of one file to another.
 * Warren Toomey 2012
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUFLEN 1024

int main(int argc, char *argv[])
{
  int infd, outfd;	/* File descriptors of the two files */
  char buffer[BUFLEN];	/* Buffer to hold part of the input file */
  ssize_t readlen;	/* Amount of data from the last read() operation */

  /* Give up if we don't have exactly 2 arguments */
  if (argc != 3) {
    printf("Usage: copy infile outfile\n"); exit(1);
  }

  /* Open up both files */
  infd= open(argv[1], O_RDONLY);
  if (infd == -1) {
    printf("Error, could not open file %s for reading\n", argv[1]); exit(1);
  }

  outfd= open(argv[2], O_WRONLY|O_CREAT, 0644);
  if (infd == -1) {
    printf("Error, could not open file %s for writing\n", argv[2]); exit(1);
  }

  /* Loop reading parts of the input file into the buffer, writing the
   * buffer out to the output file, until the read operation fails.
   */
  while (1) {
    readlen= read(infd, buffer, BUFLEN);
    if (readlen <= 0) break;
    write(outfd, buffer, readlen);
  }
 
  /* Copying done, close both files */
  close(infd);
  close(outfd);

  exit(0);
}
