cat.c (966B)
1 #include <fcntl.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 6 // cat takes N file names as command-line arguments, concatenates their 7 // contents, and writes the result to its standard output. 8 9 static char buf[4096]; 10 11 int main(int argc, char *argv[]) { 12 // Skip the first argument (program name). 13 for (int i = 1; i < argc; ++i) { 14 // Open the file. 15 int fd = open(argv[i], O_RDONLY); 16 if (fd == 0) { 17 perror("failed to open"); 18 return 1; 19 } 20 21 // Read the file into the buffer, then print it to stdout. 22 ssize_t count; 23 while ((count = read(fd, &buf, sizeof(buf))) != 0) { 24 if (count < 1) { 25 perror("failed to read"); 26 return 1; 27 } 28 // To prevent printing contents from a read that 29 // didn't fill the buffer, terminate the string. 30 if ((size_t) count < sizeof(buf)) { 31 buf[count] = '\0'; 32 } 33 34 printf("%s", buf); 35 }; 36 37 // Close the file descriptor. 38 if (close(fd) != 0) { 39 perror("failed to close"); 40 } 41 } 42 }