/
exercise_1-20.c
executable file
·84 lines (67 loc) · 1.68 KB
/
exercise_1-20.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
#include <stdio.h>
/* A program that replaces tabs in the input with the proper number of blanks
* to space to the next tab stop. Assumme tab stops every n columns.
*
* Question: Should n be a variable or symbolic parameter?
* Answer: Variable if you want to be able to read it in/parameterize it.
*/
#define TABSTOP 4 /* Tabs every x columns */
#define MAXLINE 100 /* maximum input line size */
int mygetline(char line[], int maxline);
void entab(char to[], char from[]);
main() {
int len; /* current line length */
char line[MAXLINE]; /* current input line */
char current[MAXLINE]; /* current line to print */
while ((len = mygetline(line, MAXLINE)) > 0) {
detab(current, line);
printf("%s", current);
}
return 0;
}
/* mygetline: read a line into s (up to lim characters), return length */
int mygetline(char s[], int lim) {
int c, i;
/* count all the characters but newline. Put all we can (lim) into s */
for (i=0; (c=getchar()) != EOF && c!='\n'; i++) {
if (i<lim) {
s[i] = c;
}
}
/* We stopped. Get the newline */
if (c=='\n') {
if (i<lim) {
s[i] = c;
}
i++;
}
/* add the null terminator to s */
if (i<lim) {
s[i] = '\0';
} else {
/* ran out of space, cut it off */
s[lim-1] = '\0';
}
return i;
}
/* copy: copy 'from' into 'to'. Remove tabs and add spaces to shift to the
next tab stop. Assume 'to' is big enough. */
void entab(char to[], char from[]) {
int i, j;
i = j = 0;
while ((to[j] = from[i]) != '\0') {
/* shift if we hit a tab */
if (to[j] == '\t') {
to[j] = ' ';
j++;
while (j % TABSTOP != 0) {
to[j] = ' ';
j++;
}
j--;
}
/* increment the indicies */
i++;
j++;
}
}