-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplace-tab-with-space.c
67 lines (56 loc) · 1.34 KB
/
replace-tab-with-space.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* Replace tab with space, and we can potentially do this in awk than
* a C program.
*
* We assume a tab is equivalent to 8 spaces, but it is not always the
* case.
*/
#include <ctype.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int space2Tab = 8;
char *programName = NULL;
void printHelp(void) {
fprintf(stderr, "%s [-h] [-t space]\n", programName);
fprintf(stderr, "\n");
fprintf(stderr, " -h : print this help message\n");
fprintf(stderr, " -t space : number of space per tab [default is 8 and must "
"be 1 or above]\n");
}
int main(int argc, char *argv[]) {
int c;
int i;
int startWithNoneSpace = 0;
programName = basename(argv[0]);
while ((c = getopt(argc, argv, "ht:")) != -1) {
switch (c) {
case 't':
space2Tab = strtol(optarg, NULL, 0);
break;
case '?':
case 'h':
printHelp();
exit(1);
}
}
if (space2Tab <= 0) {
printHelp();
exit(1);
}
while ((c = getchar()) != EOF) {
if ('\t' == c && !startWithNoneSpace) {
for (i = 0; i < space2Tab; i++)
putchar(' ');
} else {
if (!isspace(c))
startWithNoneSpace = 1;
else if ('\n' == c)
startWithNoneSpace = 0;
putchar(c);
}
}
return 0;
}