1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * %sccs.include.redist.c%
6 */
7
8 #ifndef lint
9 static char copyright[] =
10 "@(#) Copyright (c) 1991, 1993\n\
11 The Regents of the University of California. All rights reserved.\n";
12 #endif /* not lint */
13
14 #ifndef lint
15 static char sccsid[] = "@(#)colrm.c 8.2 (Berkeley) 05/04/95";
16 #endif /* not lint */
17
18 #include <sys/types.h>
19 #include <limits.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25
26 #define TAB 8
27
28 void err __P((const char *, ...));
29 void check __P((FILE *));
30 void usage __P((void));
31
32 int
main(argc,argv)33 main(argc, argv)
34 int argc;
35 char *argv[];
36 {
37 register u_long column, start, stop;
38 register int ch;
39 char *p;
40
41 while ((ch = getopt(argc, argv, "")) != EOF)
42 switch(ch) {
43 case '?':
44 default:
45 usage();
46 }
47 argc -= optind;
48 argv += optind;
49
50 start = stop = 0;
51 switch(argc) {
52 case 2:
53 stop = strtol(argv[1], &p, 10);
54 if (stop <= 0 || *p)
55 err("illegal column -- %s", argv[1]);
56 /* FALLTHROUGH */
57 case 1:
58 start = strtol(argv[0], &p, 10);
59 if (start <= 0 || *p)
60 err("illegal column -- %s", argv[0]);
61 break;
62 case 0:
63 break;
64 default:
65 usage();
66 }
67
68 if (stop && start > stop)
69 err("illegal start and stop columns");
70
71 for (column = 0;;) {
72 switch (ch = getchar()) {
73 case EOF:
74 check(stdin);
75 break;
76 case '\b':
77 if (column)
78 --column;
79 break;
80 case '\n':
81 column = 0;
82 break;
83 case '\t':
84 column = (column + TAB) & ~(TAB - 1);
85 break;
86 default:
87 ++column;
88 break;
89 }
90
91 if ((!start || column < start || stop && column > stop) &&
92 putchar(ch) == EOF)
93 check(stdout);
94 }
95 }
96
97 void
check(stream)98 check(stream)
99 FILE *stream;
100 {
101 if (feof(stream))
102 exit(0);
103 if (ferror(stream))
104 err("%s: %s",
105 stream == stdin ? "stdin" : "stdout", strerror(errno));
106 }
107
108 void
usage()109 usage()
110 {
111 (void)fprintf(stderr, "usage: colrm [start [stop]]\n");
112 exit(1);
113 }
114
115 #if __STDC__
116 #include <stdarg.h>
117 #else
118 #include <varargs.h>
119 #endif
120
121 void
122 #if __STDC__
err(const char * fmt,...)123 err(const char *fmt, ...)
124 #else
125 err(fmt, va_alist)
126 char *fmt;
127 va_dcl
128 #endif
129 {
130 va_list ap;
131 #if __STDC__
132 va_start(ap, fmt);
133 #else
134 va_start(ap);
135 #endif
136 (void)fprintf(stderr, "colrm: ");
137 (void)vfprintf(stderr, fmt, ap);
138 va_end(ap);
139 (void)fprintf(stderr, "\n");
140 exit(1);
141 /* NOTREACHED */
142 }
143