1 #include <stdio.h> 2 #include <unistd.h> 3 #include <stdlib.h> 4 #include <sys/types.h> 5 #include <sys/stat.h> 6 #include <fcntl.h> 7 #include "version.h" 8 #include "cat.h" 9 10 int cat_main (int argc, char **argv) { 11 char buf[1024]; 12 int error_code=0; 13 int i,x; 14 int fd=-1; 15 16 /* If no input files are given on the command line, use STDIN instead. */ 17 if (argc==1) { 18 fd=STDIN_FILENO; 19 argc++; 20 } 21 22 23 /* Loop through files given on the command line*/ 24 25 for (i=1;i<argc;i++) { 26 /* Make sure we're not supposed to be reading STDIN */ 27 if (fd==-1) { 28 /* If there is an error, print it and continue loop */ 29 if ((fd=open(argv[i],O_RDONLY))<0) { 30 write(STDERR_FILENO, "cat: ", 5); 31 perror(argv[i]); 32 error_code=-1; 33 goto loop; 34 } 35 } 36 /* Read the file in 1024 byte sections until we encounter the end. */ 37 while (1) { 38 if ((x=read(fd, &buf, 1024))<1) break; 39 write(STDOUT_FILENO, &buf, x); 40 } 41 close(fd); 42 loop: 43 } 44 45 /* If there were any errors, exit in error. */ 46 47 return(error_code); 48 } |