xref: /original-bsd/usr.bin/fold/fold.c (revision 262b24ac)
1 /*
2  * Copyright (c) 1980 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1980 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)fold.c	5.2 (Berkeley) 06/29/88";
26 #endif /* not lint */
27 
28 #include <stdio.h>
29 /*
30  * fold - fold long lines for finite output devices
31  *
32  * Bill Joy UCB June 28, 1977
33  */
34 
35 int	fold =  80;
36 
37 main(argc, argv)
38 	int argc;
39 	char *argv[];
40 {
41 	register c;
42 	FILE *f;
43 
44 	argc--, argv++;
45 	if (argc > 0 && argv[0][0] == '-') {
46 		fold = 0;
47 		argv[0]++;
48 		while (*argv[0] >= '0' && *argv[0] <= '9')
49 			fold *= 10, fold += *argv[0]++ - '0';
50 		if (*argv[0]) {
51 			printf("Bad number for fold\n");
52 			exit(1);
53 		}
54 		argc--, argv++;
55 	}
56 	do {
57 		if (argc > 0) {
58 			if (freopen(argv[0], "r", stdin) == NULL) {
59 				perror(argv[0]);
60 				exit(1);
61 			}
62 			argc--, argv++;
63 		}
64 		for (;;) {
65 			c = getc(stdin);
66 			if (c == -1)
67 				break;
68 			putch(c);
69 		}
70 	} while (argc > 0);
71 	exit(0);
72 }
73 
74 int	col;
75 
76 putch(c)
77 	register c;
78 {
79 	register ncol;
80 
81 	switch (c) {
82 		case '\n':
83 			ncol = 0;
84 			break;
85 		case '\t':
86 			ncol = (col + 8) &~ 7;
87 			break;
88 		case '\b':
89 			ncol = col ? col - 1 : 0;
90 			break;
91 		case '\r':
92 			ncol = 0;
93 			break;
94 		default:
95 			ncol = col + 1;
96 	}
97 	if (ncol > fold)
98 		putchar('\n'), col = 0;
99 	putchar(c);
100 	switch (c) {
101 		case '\n':
102 			col = 0;
103 			break;
104 		case '\t':
105 			col += 8;
106 			col &= ~7;
107 			break;
108 		case '\b':
109 			if (col)
110 				col--;
111 			break;
112 		case '\r':
113 			col = 0;
114 			break;
115 		default:
116 			col++;
117 			break;
118 	}
119 }
120