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 #define FMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) 11 main() 12 { 13 char buf[BUFSIZ]; 14 char PROMPT1[] = "Please enter source filename >> "; 15 char PROMPT2[] = "Please enter target filename >> "; 16 char ERR1[] = "Can't open source file\n"; 17 char ERR2[] = "Can't open target file\n"; 18 char ERR3[] = "Can't read source file\n"; 19 int fd1, fd2; 20 ssize_t nread; 21 write(STDOUT_FILENO, PROMPT1, strlen(PROMPT1)); /* ask for input file */ 22 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 23 buf[nread-1] = '\0'; /* strip \n & NULL-terminate buf */ 24 if ((fd1 = open(buf, O_RDONLY)) == -1) { /* open for read */ 25 write(STDERR_FILENO, ERR1, strlen(ERR1)); /* write to stderr */ 26 return(1); 27 } 28 write(STDOUT_FILENO, PROMPT2, strlen(PROMPT2)); /* ask for output file */ 29 nread = read(STDIN_FILENO, buf, BUFSIZ); /* read from stdin */ 30 buf[nread-1] = '\0'; /* strip \n & NULL-terminate str */ 31 if ((fd2 = open(buf, O_WRONLY | O_CREAT | O_TRUNC, FMODE)) == -1) { 32 write(STDERR_FILENO, ERR2, strlen(ERR2)); /* write to stderr */ 33 return(2); 34 } 35 while ((nread = read(fd1, buf, BUFSIZ)) > 0) { /* while not EOF */ 36 write(fd2, buf, nread); /* save to file 2 */ 37 } 38 if (nread < 0) { 39 write(STDERR_FILENO, ERR3, strlen(ERR3)); /* write to stderr */ 40 return(3); 41 } 42 close(fd1); 43 close(fd2); 44 exit(0); 45 }