Advertisement
rfmonk

copy.c

Dec 26th, 2013
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <sys/stat.h>
  2. #include <fcntl.h>
  3. #include "tlpi_hdr.h"
  4.  
  5. #ifndef BUF-SIZE                /* allow "cc -D" to override definition */
  6. #define BUF_SIZE 1024
  7. #endif
  8.  
  9. int
  10. main(int argc, char *argv[])
  11. {
  12.     int inputFd, outputFd, openFlags;
  13.     mode_t filePerms;
  14.     ssize_t numRead;
  15.     char buf[BUF_SIZE];
  16.  
  17.     if (argc != 3 || strcmp(argv[1], "--help") == 0)
  18.         usageErr("%s old-file new-file\n", argv[0]);
  19.  
  20.     /* Open input and output files */
  21.  
  22.     inputFd = open(argv[1], O_RDONLY);
  23.     if (inputFd == -1)
  24.         errExit("opening file %s", argv[1]);
  25.  
  26.     openFlags = O_CREAT | O_WRONGLY | O_TRUNC;
  27.     filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
  28.                 S_IROTH | S_IWOTH;      /* rw- rw- rw- */
  29.     outputFd = open(argv[2], openFlags, filePerms);
  30.     if (outputFd == -1)
  31.         errExit("opening file %s", argv[2]);
  32.  
  33.     /* Transfer data until we encounter end of input or an error */
  34.  
  35.     while ((numRead = read(inputFd, buf, BUF_SIZE)) > 0)
  36.         if (write(outputFd, buf, numRead) != numRead)
  37.             fatal("couldn't write whole buffer");
  38.     if (numRead == -1)
  39.         errExit("read");
  40.  
  41.     if (close(inputFd) == -1)
  42.         errExit("read");
  43.  
  44.     if (close(inputFd) == -1)
  45.         errExit("close input");
  46.     if (close(outputFd) == -1)
  47.         errExit("close output");
  48.  
  49.     exit(EXIT_SUCCESS);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement