/
pad_backslash.c
115 lines (98 loc) · 2.73 KB
/
pad_backslash.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//---------------------------------------------------------------------------//
// vim: sw=4 ts=4 expandtab
//---------------------------------------------------------------------------//
//
// Copyright (C) 2006 The University of Melbourne.
// This file may only be copied under the terms of the GNU General
// Public License - see the file COPYING in the Mercury distribution.
//
// File: pad_backslash.c
// Author: zs
//
// Given an input stream in which some lines end with backslashes, pad those
// lines with spaces so that the backslashes are in column 77.
//
//---------------------------------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// options and arguments, set by parse_options().
static int target_column = 77;
static void usage(void);
static void process(FILE *fp);
/*---------------------------------------------------------------------------*/
int
main(int argc, char **argv)
{
int opt;
int num_files;
while ((opt = getopt(argc, argv, "c:")) != EOF) {
switch (opt) {
case 'c':
if (sscanf(optarg, "%d", &target_column) != 1) {
usage();
}
break;
default:
usage();
}
}
num_files = argc - optind;
if (num_files == 0) {
process(stdin);
} else if (num_files == 1) {
FILE *fp;
fp = fopen(argv[optind], "r");
if (fp != NULL) {
process(fp);
(void) fclose(fp);
} else {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
return EXIT_SUCCESS;
}
static void
usage(void)
{
fputs("Usage: pad_backslash [-c column] [inputfile]\n", stderr);
exit(EXIT_FAILURE);
}
static void
process(FILE *fp)
{
int cur_column;
int cur_char;
int next_char;
cur_column = 1;
while ((cur_char = getc(fp)) != EOF) {
if (cur_char == '\n') {
putchar(cur_char);
cur_column = 1;
} else if (cur_char == '\\') {
next_char = getc(fp);
if (next_char == '\n') {
while (cur_column < target_column) {
putchar(' ');
cur_column++;
}
putchar(cur_char);
putchar(next_char);
cur_column = 1;
} else {
putchar(cur_char);
putchar(next_char);
cur_column++;
}
} else if (cur_char == '\t') {
while (cur_column % 8 != 0) {
putchar(' ');
cur_column++;
}
} else {
putchar(cur_char);
cur_column++;
}
}
}