]> pd.if.org Git - pdutils/blob - posix/cat/cat.c
rename utils to posix
[pdutils] / posix / cat / cat.c
1 /*
2  * cat.c - concatenate file(s) to standard output
3  *
4  * Version: 2008-1.01
5  * Build:   c89 -o cat cat.c
6  * Source:  <http://pdcore.sourceforge.net/>
7  * Spec:    <http://www.opengroup.org/onlinepubs/9699919799/utilities/cat.html>
8  *
9  * This is free and unencumbered software released into the public domain,
10  * provided "as is", without warranty of any kind, express or implied. See the
11  * file UNLICENSE and the website <http://unlicense.org> for further details.
12  */
13
14
15 #define _POSIX_SOURCE
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <locale.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24
25 #define USAGE   "usage: cat [-u] [file ...]\n"
26 #define BUFSIZE 4096
27
28 static void catfile(int fd, char *fn);
29 static void error(char *s);
30
31 static int exitstatus;
32 static int optu;
33
34
35 int main(int argc, char **argv) {
36     extern int opterr, optind;
37     int c, fd;
38     char *fn;
39
40     setlocale(LC_ALL, "");
41     opterr = 0;
42
43     while ((c = getopt(argc, argv, "u")) != -1)
44         switch (c) {
45         case 'u':
46             optu = 1;
47             break;
48         default:
49             fprintf(stderr, USAGE);
50             return(1);
51         }
52
53     if (optind >= argc)
54         catfile(STDIN_FILENO, "stdin");
55     else
56         while (optind < argc)
57         {
58             fn = argv[optind++];
59
60             if (strcmp(fn, "-") == 0)
61                 catfile(STDIN_FILENO, "stdin");
62             else
63                 if ((fd = open(fn, O_RDONLY)) == -1)
64                     error(fn);
65                 else
66                 {
67                     catfile(fd, fn);
68                     if (close(fd) == -1)
69                         error(fn);
70                 }
71         }
72
73     return(exitstatus);
74 }
75
76 void catfile(int fd, char *fn) {
77     unsigned char buf[BUFSIZE];
78     ssize_t n;
79
80     while ((n = read(fd, buf, (optu ? 1 : BUFSIZE))) > 0)
81         if (write(STDOUT_FILENO, buf, (size_t)n) != n) {
82             error("stdout");
83             break;
84         }
85
86     if (n < 0) error(fn);
87 }
88
89 void error(char *s) {
90     fprintf(stderr, "cat: %s: %s\n", s, strerror(errno));
91     exitstatus = 1;
92 }