blob: 30fe789e8b8db699a7ff7fc94f8acfc3dd1bbce1 [file] [log] [blame]
Jari Aaltoccc6cda1996-12-23 17:02:34 +00001/*
2 * cat replacement
3 *
4 * no options - the way cat was intended
5 */
6
Jari Aalto31859422009-01-12 13:36:28 +00007/*
8 Copyright (C) 1999-2009 Free Software Foundation, Inc.
9
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.
15
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.
20
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/>.
23*/
24
Jari Aaltoccc6cda1996-12-23 17:02:34 +000025#include <fcntl.h>
26#include <errno.h>
27
28#include "builtins.h"
29#include "shell.h"
30
31#ifndef errno
Ricardo Cerqueiraa02fbff2013-07-25 22:35:34 +010032#include <errno.h>
Jari Aaltoccc6cda1996-12-23 17:02:34 +000033#endif
34
35extern char *strerror ();
36extern char **make_builtin_argv ();
37
38static int
39fcopy(fd)
40int fd;
41{
42 char buf[1024], *s;
43 int n, w, e;
44
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;
54 }
55 }
56 return 0;
57}
58
59cat_main (argc, argv)
60int argc;
61char **argv;
62{
63 int i, fd, r;
64 char *s;
65
66 if (argc == 1)
67 return (fcopy(0));
68
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;
82 }
83 }
84 r = fcopy(fd);
85 if (fd != 0)
86 close(fd);
87 }
88 return (r);
89}
90
91cat_builtin(list)
92WORD_LIST *list;
93{
94 char **v;
95 int c, r;
96
97 v = make_builtin_argv(list, &c);
98 r = cat_main(c, v);
99 free(v);
100
101 return r;
102}
103
104char *cat_doc[] = {
Jari Aalto31859422009-01-12 13:36:28 +0000105 "Display files.",
106 "",
Jari Aaltoccc6cda1996-12-23 17:02:34 +0000107 "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
111};
112
113struct builtin cat_struct = {
114 "cat",
115 cat_builtin,
116 BUILTIN_ENABLED,
117 cat_doc,
118 "cat [-] [file ...]",
119 0
120};