1 /* fileCopy.c 2 This example shows how to do file copy, one block at a time. 3 System calls used in this program: 4 . write(), read(), open(), close(), exit(). 5 */ 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #define FMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) 13 main() 14 { 15 char buf[BUFSIZ]; 16 char PROMPT1[] = "Please enter source filename >> "; 17 char PROMPT2[] = "Please enter target filename >> "; 18 char ERR1[] = "Can't open source file\n"; 19 char ERR2[] = "Can't open target file\n"; 20 char ERR3[] = "Can't read source file\n"; 21 int fd1, fd2; 22 ssize_t nread; 23 write(STDOUT_FILENO, PROMPT1, strlen(PROMPT1)); /* ask for input file */ 24 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 25 buf[nread-1] = '\0'; /* strip \n & NULL-terminate buf */ 26 if ((fd1 = open(buf, O_RDONLY)) == -1) { /* open for read */ 27 write(STDERR_FILENO, ERR1, strlen(ERR1)); /* write to stderr */ 28 return(1); 29 } 30 write(STDOUT_FILENO, PROMPT2, strlen(PROMPT2)); /* ask for output file */ 31 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 32 buf[nread-1] = '\0'; /* strip \n & NULL-terminate str */ 33 if ((fd2 = open(buf, O_WRONLY | O_CREAT | O_TRUNC, FMODE)) == -1) { 34 write(STDERR_FILENO, ERR2, strlen(ERR2)); /* write to stderr */ 35 return(2); 36 } 37 while ((nread = read(fd1, buf, BUFSIZ)) > 0) { /* while not EOF */ 38 write(fd2, buf, nread); /* save to file 2 */ 39 } 40 if (nread < 0) { 41 write(STDERR_FILENO, ERR3, strlen(ERR3)); /* write to stderr */ 42 return(3); 43 } 44 close(fd1); 45 close(fd2); 46 exit(0); 47 }