date and time created 80/10/30 00:40:38 by mckusick
[unix-history] / usr / src / bin / cat / cat.c
CommitLineData
efa30d97
BJ
1/*
2 * Concatenate files.
3 */
3c67f80d 4static char *Sccsid = "@(#)cat.c 4.2 (Berkeley) %G%";
efa30d97
BJ
5
6#include <stdio.h>
7#include <sys/types.h>
8#include <sys/stat.h>
9
10char stdbuf[BUFSIZ];
3c67f80d
BJ
11int bflg, eflg, nflg, sflg, tflg, vflg;
12int spaced, col, lno, inline;
efa30d97
BJ
13
14main(argc, argv)
15char **argv;
16{
17 int fflg = 0;
18 register FILE *fi;
19 register c;
20 int dev, ino = -1;
21 struct stat statb;
22
3c67f80d 23 lno = 1;
efa30d97
BJ
24 setbuf(stdout, stdbuf);
25 for( ; argc>1 && argv[1][0]=='-'; argc--,argv++) {
26 switch(argv[1][1]) {
27 case 0:
28 break;
29 case 'u':
30 setbuf(stdout, (char *)NULL);
31 continue;
3c67f80d
BJ
32 case 'n':
33 nflg++;
34 continue;
35 case 'b':
36 bflg++;
37 nflg++;
38 continue;
39 case 'v':
40 vflg++;
41 continue;
42 case 's':
43 sflg++;
44 continue;
45 case 'e':
46 eflg++;
47 vflg++;
48 continue;
49 case 't':
50 tflg++;
51 vflg++;
52 continue;
efa30d97
BJ
53 }
54 break;
55 }
56 fstat(fileno(stdout), &statb);
57 statb.st_mode &= S_IFMT;
58 if (statb.st_mode!=S_IFCHR && statb.st_mode!=S_IFBLK) {
59 dev = statb.st_dev;
60 ino = statb.st_ino;
61 }
62 if (argc < 2) {
63 argc = 2;
64 fflg++;
65 }
66 while (--argc > 0) {
67 if (fflg || (*++argv)[0]=='-' && (*argv)[1]=='\0')
68 fi = stdin;
69 else {
70 if ((fi = fopen(*argv, "r")) == NULL) {
71 fprintf(stderr, "cat: can't open %s\n", *argv);
72 continue;
73 }
74 }
75 fstat(fileno(fi), &statb);
76 if (statb.st_dev==dev && statb.st_ino==ino) {
77 fprintf(stderr, "cat: input %s is output\n",
78 fflg?"-": *argv);
79 fclose(fi);
80 continue;
81 }
3c67f80d
BJ
82 if (nflg||sflg||vflg)
83 copyopt(fi);
84 else {
85 while ((c = getc(fi)) != EOF)
86 putchar(c);
87 }
efa30d97
BJ
88 if (fi!=stdin)
89 fclose(fi);
90 }
3c67f80d
BJ
91 if (ferror(stdout))
92 fprintf(stderr, "cat: output write error\n");
efa30d97
BJ
93 return(0);
94}
3c67f80d
BJ
95
96copyopt(f)
97 register FILE *f;
98{
99 register int c;
100
101top:
102 c = getc(f);
103 if (c == EOF)
104 return;
105 if (c == '\n') {
106 if (inline == 0) {
107 if (sflg && spaced)
108 goto top;
109 spaced = 1;
110 }
111 if (nflg && bflg==0 && inline == 0)
112 printf("%6d\t", lno++);
113 if (eflg)
114 putchar('$');
115 putchar('\n');
116 inline = 0;
117 goto top;
118 }
119 if (nflg && inline == 0)
120 printf("%6d\t", lno++);
121 inline = 1;
122 if (vflg) {
123 if (tflg==0 && c == '\t')
124 putchar(c);
125 else {
126 if (c > 0177) {
127 printf("M-");
128 c &= 0177;
129 }
130 if (c < ' ')
131 printf("^%c", c+'@');
132 else if (c == 0177)
133 printf("^?");
134 else
135 putchar(c);
136 }
137 } else
138 putchar(c);
139 spaced = 0;
140 goto top;
141}