-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrm_trailspace.c
66 lines (52 loc) · 1.39 KB
/
rm_trailspace.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
/* remove trailing whitespace */
#include <stdio.h>
#define MAXLINE 1000
#define IS_CHAR 0
#define IS_BLANK 1
int getline(char line[], int maxline);
int rm_whitespace(char line[], int len);
int is_whitespace(char c);
main()
{
int len;
char line[MAXLINE];
/* get the line */
while((len = getline(line, MAXLINE)) > 0){
rm_whitespace(line, len);
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;
}
/* rm_whitespace: remove trailing blanks, tabs and blank lines */
int rm_whitespace(char line[], int len)
{
/* trim length until we get rid of all whitespace */
while(len && is_whitespace(line[len-1]))
--len;
/* set newline and null*/
if(len){ /* not blank line*/
line[len] = '\n';
line[len+1] = '\0';
}
else
line[len] = '\0'; /* blank line */
line[len+1] = '\0';
return len;
}
int is_whitespace(char c) { return c == ' ' || c == '\n' || c == '\t'; }