-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetab.c
80 lines (64 loc) · 1.82 KB
/
detab.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
/* Replaces tabs in input with appropriate number of spaces */
#include <stdio.h>
#include <stdlib.h>
#define TABSTOP 4
#define MAXLINE 1000
int getline(char line[], int maxline);
int detab(char s[], int len, int tabstop);
main(int argc, char *argv[])
{
int len, tabstop;
char line[MAXLINE];
tabstop = 0;
if(argc == 2)
tabstop = atoi(argv[1]); /* assign the tabstop */
while((len = getline(line, MAXLINE)) > 0){
len = detab(line, len, tabstop);
if(!len)
printf("Detab failed: len exceeds MAXLINE\n");
else
printf("%s", line);
}
return 0;
}
/* getline: read a line, return length */
int getline(char line[], int maxline)
{
int c; /* character returned by getchar */
int i; /* array index*/
/* fill line until we reach maxline-1 length, EOF or newline */
for(i = 0; i < maxline-1 && (c=getchar()) != EOF && c != '\n'; ++i)
line[i] = c;
/* add newline character and null termination character */
if(c == '\n'){
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
/* detab: turns tabs into spaces
* returns len of new array on success, 0 on fail */
int detab(char s[], int len, int tabstop)
{
int newlen;
int i, j;
if(!tabstop)
tabstop = TABSTOP;
for (i = 0; i < len; ++i) {
if(s[i] == '\t') {
len += tabstop - 1; /* update len to account for tabstop */
/* return 0 on fail*/
if(len > MAXLINE)
return 0;
/* shift char array to the right, by "tabstop" */
for(j = len-1; j >= i+tabstop; --j)
s[j] = s[j-tabstop+1];
s[len] = '\0';
/* replace tab with spaces */
for(j = i; j < i+tabstop; ++j)
s[j] = ' ';
}
}
return len;
}