source: trunk/minix/commands/simple/unexpand.c@ 15

Last change on this file since 15 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 2.2 KB
Line 
1/* unexpand - convert spaces to tabs Author: Terrence W. Holm */
2
3/* Usage: unexpand [ -a ] [ file ... ] */
4
5#include <stdlib.h>
6#include <string.h>
7#include <stdio.h>
8
9#define TAB 8
10
11
12int column = 0; /* Current column, retained between files */
13int spaces = 0; /* Spaces since last tab stop */
14int leading_blank = 1; /* Only unexpand leading blanks, */
15/* Overruled by -a option */
16
17_PROTOTYPE(int main, (int argc, char **argv));
18_PROTOTYPE(void Unexpand, (FILE *f, int all));
19
20int main(argc, argv)
21int argc;
22char *argv[];
23
24{
25 int all = 0; /* -a flag means unexpand all spaces */
26 int i;
27 FILE *f;
28
29 if (argc > 1 && argv[1][0] == '-') {
30 if (strcmp(argv[1], "-a") == 0)
31 all = 1;
32 else {
33 fprintf(stderr, "Usage: unexpand [ -a ] [ file ... ]\n");
34 exit(1);
35 }
36
37 --argc;
38 ++argv;
39 }
40 if (argc == 1)
41 Unexpand(stdin, all);
42 else
43 for (i = 1; i < argc; ++i) {
44 if ((f = fopen(argv[i], "r")) == NULL) {
45 perror(argv[i]);
46 exit(1);
47 }
48 Unexpand(f, all);
49 fclose(f);
50 }
51
52
53 /* If there are pending spaces print them. */
54
55 while (spaces > 0) {
56 putchar(' ');
57 --spaces;
58 }
59
60 return(0);
61}
62
63void Unexpand(f, all)
64FILE *f;
65int all;
66
67{
68 int c;
69
70 while ((c = getc(f)) != EOF) {
71 if (c == ' ' && (all || leading_blank)) {
72 ++column;
73 ++spaces;
74
75 /* If we have white space up to a tab stop, then output */
76 /* A tab. If only one space is required, use a ' '. */
77
78 if (column % TAB == 0) {
79 if (spaces == 1)
80 putchar(' ');
81 else
82 putchar('\t');
83
84 spaces = 0;
85 }
86 continue;
87 }
88
89 /* If a tab character is encountered in the input then */
90 /* Simply echo it. Any accumulated spaces can only be */
91 /* Since the last tab stop, so ignore them. */
92 if (c == '\t') {
93 column = (column / TAB + 1) * TAB;
94 spaces = 0;
95 putchar('\t');
96 continue;
97 }
98
99 /* A non-space character is to be printed. If there */
100 /* Are pending spaces, then print them. There will be */
101 /* At most TAB-1 spaces to print. */
102 while (spaces > 0) {
103 putchar(' ');
104 --spaces;
105 }
106
107 if (c == '\n' || c == '\r') {
108 column = 0;
109 leading_blank = 1;
110 putchar(c);
111 continue;
112 }
113 if (c == '\b')
114 column = column > 0 ? column - 1 : 0;
115 else
116 ++column;
117
118 leading_blank = 0;
119 putchar(c);
120 }
121}
Note: See TracBrowser for help on using the repository browser.