Created
August 2, 2013 21:10
-
-
Save meikj/6143503 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define MAXLINE 1000 | |
#define NEWLINE_ON 1 | |
#define NEWLINE_OFF 0 | |
int strend(char string[], int len); | |
int getline(char line[], int maxline); | |
int main(void) { | |
int len, end, newline, count; | |
char line[MAXLINE]; | |
count = 0; | |
newline = NEWLINE_OFF; | |
while ( (len = getline(line, MAXLINE)) > 0 ) { | |
if (line[0] == '\n') | |
continue; | |
for (end = strend(line, MAXLINE); end >= 0; --end) { | |
if (line[end] == '\n') { | |
// Set newline to NEWLINE_ON so we can append a newline later | |
newline = NEWLINE_ON; | |
line[end] = '\0'; | |
} else if (line[end] == ' ' || line[end] == '\t') { | |
// Null terminate trailing whitespace or tabs | |
line[end] = '\0'; | |
++count; | |
} else { | |
// We've reached non-trailing whitespace/tab, so we're finished | |
break; | |
} | |
} | |
if(newline == NEWLINE_ON) { | |
// Append a new line character as original string contained one | |
line[++end] = '\n'; | |
} | |
printf("%s", line); | |
} | |
printf("\nRemoved %d trailing whitespace(s)\n", count); | |
return 0; | |
} | |
int strend(char string[], int len) { | |
int i; | |
for (i = 0; i < len; ++i) { | |
if (string[i] == '\0') | |
return (i-1); // -1 for "human" end of string (before '\0') | |
} | |
return 0; | |
} | |
int getline(char line[], int maxline) { | |
int c, i; | |
for (i = 0; i < (maxline-1) && (c = getchar()) != EOF && c != '\n'; ++i) | |
line[i] = c; | |
if (c == '\n') { | |
line[i] = '\n'; | |
++i; | |
} | |
line[i] = '\0'; | |
return i; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment