ex-4.7.c (1132B)
1 /* 2 * Advanced Programming in the UNIX(r) Environment 3 * 4 * Exercise 4.7 5 */ 6 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <unistd.h> 10 #include <fcntl.h> 11 #include <sys/stat.h> 12 13 #define BUFSIZE 8192 14 15 int 16 main(int argc, char *argv[]) 17 { 18 int fd, fd2; 19 ssize_t size; 20 char buf[BUFSIZE] = { 0 }; 21 22 /* Arguments check */ 23 if( argc != 3 ) { 24 printf("Usage: %s <source file> <destination file>\n", argv[0]); 25 return EXIT_FAILURE; 26 } 27 28 /* open the source file */ 29 if( (fd = open(argv[1], O_RDONLY)) == -1 ) { 30 perror("open(source)"); 31 return EXIT_FAILURE; 32 } 33 34 /* open the destination file */ 35 if( (fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1 ) { 36 perror("open(destination)"); 37 38 close(fd); /* close the source file */ 39 return EXIT_FAILURE; 40 } 41 42 /* copy the file */ 43 while( (size = read(fd, buf, 1)) > 0 ) { 44 if( *buf && write(fd2, buf, size) != size ) { 45 perror("write"); 46 break; 47 } 48 } 49 50 /* read error */ 51 if( size == -1 ) 52 perror("read"); 53 54 close(fd); 55 close(fd2); 56 57 return EXIT_SUCCESS; 58 } /* eof main() */ 59