xref: /original-bsd/bin/cat/cat.c (revision ba72ef4c)
1 /*
2  * Concatenate files.
3  */
4 static	char *Sccsid = "@(#)cat.c	4.2 (Berkeley) 10/10/80";
5 
6 #include <stdio.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 
10 char	stdbuf[BUFSIZ];
11 int	bflg, eflg, nflg, sflg, tflg, vflg;
12 int	spaced, col, lno, inline;
13 
14 main(argc, argv)
15 char **argv;
16 {
17 	int fflg = 0;
18 	register FILE *fi;
19 	register c;
20 	int dev, ino = -1;
21 	struct stat statb;
22 
23 	lno = 1;
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;
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;
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 		}
82 		if (nflg||sflg||vflg)
83 			copyopt(fi);
84 		else {
85 			while ((c = getc(fi)) != EOF)
86 				putchar(c);
87 		}
88 		if (fi!=stdin)
89 			fclose(fi);
90 	}
91 	if (ferror(stdout))
92 		fprintf(stderr, "cat: output write error\n");
93 	return(0);
94 }
95 
96 copyopt(f)
97 	register FILE *f;
98 {
99 	register int c;
100 
101 top:
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 }
142