Advertisement
Maco153

simple cp program

Aug 6th, 2022 (edited)
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. /* File copy program. Error checking and reporting is minimal. */
  2. #include <sys/types.h> /* include necessary header files */
  3. #include <fcntl.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. int main(int argc, char *argv[]); /* ANSI prototype */
  7. #define BUF SIZE 4096 /* use a buffer size of 4096 bytes */
  8. #define OUTPUT MODE 0700 /* protection bits for output file */
  9. int main(int argc, char *argv[])
  10. {
  11. int in fd, out fd, rd count, wt count;
  12. char buffer[BUF SIZE];
  13. if (argc != 3) exit(1); /* syntax error if argc is not 3 */
  14. /* Open the input file and create the output file */
  15. in fd = open(argv[1], O RDONLY); /* open the source file */
  16. if (in fd < 0) exit(2); /* if it cannot be opened, exit */
  17. out fd = creat(argv[2], OUTPUT MODE); /* create the destination file */
  18. if (out fd < 0) exit(3); /* if it cannot be created, exit */
  19. /* Copy loop */
  20. while (TRUE) {
  21. rd count = read(in fd, buffer, BUF SIZE); /* read a block of data */
  22. if (rd count <= 0) break; /* if end of file or error, exit loop */
  23. wt count = write(out fd, buffer, rd count); /* write data */
  24. if (wt count <= 0) exit(4); /* wt count <= 0 is an error */
  25. } /
  26. * Close the files */
  27. close(in fd);
  28. close(out fd);
  29. if (rd count == 0) /* no error on last read */
  30. exit(0);
  31. else
  32. exit(5); /* error on last read */
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement