Patch-ID: bash41-003
[bash.git] / examples / loadables / cat.c
blob1ce2e2dc48a8464d3d161afecd35971533ed2481
1 /*
2 * cat replacement
4 * no options - the way cat was intended
5 */
7 /*
8 Copyright (C) 1999-2009 Free Software Foundation, Inc.
10 This file is part of GNU Bash.
11 Bash is free software: you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or
14 (at your option) any later version.
16 Bash is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with Bash. If not, see <http://www.gnu.org/licenses/>.
25 #include <fcntl.h>
26 #include <errno.h>
28 #include "builtins.h"
29 #include "shell.h"
31 #ifndef errno
32 extern int errno;
33 #endif
35 extern char *strerror ();
36 extern char **make_builtin_argv ();
38 static int
39 fcopy(fd)
40 int fd;
42 char buf[1024], *s;
43 int n, w, e;
45 while (n = read(fd, buf, sizeof (buf))) {
46 w = write(1, buf, n);
47 if (w != n) {
48 e = errno;
49 write(2, "cat: write error: ", 18);
50 s = strerror(e);
51 write(2, s, strlen(s));
52 write(2, "\n", 1);
53 return 1;
56 return 0;
59 cat_main (argc, argv)
60 int argc;
61 char **argv;
63 int i, fd, r;
64 char *s;
66 if (argc == 1)
67 return (fcopy(0));
69 for (i = r = 1; i < argc; i++) {
70 if (argv[i][0] == '-' && argv[i][1] == '\0')
71 fd = 0;
72 else {
73 fd = open(argv[i], O_RDONLY, 0666);
74 if (fd < 0) {
75 s = strerror(errno);
76 write(2, "cat: cannot open ", 17);
77 write(2, argv[i], strlen(argv[i]));
78 write(2, ": ", 2);
79 write(2, s, strlen(s));
80 write(2, "\n", 1);
81 continue;
84 r = fcopy(fd);
85 if (fd != 0)
86 close(fd);
88 return (r);
91 cat_builtin(list)
92 WORD_LIST *list;
94 char **v;
95 int c, r;
97 v = make_builtin_argv(list, &c);
98 r = cat_main(c, v);
99 free(v);
101 return r;
104 char *cat_doc[] = {
105 "Display files.",
107 "Read each FILE and display it on the standard output. If any",
108 "FILE is `-' or if no FILE argument is given, the standard input",
109 "is read.",
110 (char *)0
113 struct builtin cat_struct = {
114 "cat",
115 cat_builtin,
116 BUILTIN_ENABLED,
117 cat_doc,
118 "cat [-] [file ...]",