diff options
Diffstat (limited to 'ch01')
| -rw-r--r-- | ch01/ex19-reverse.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/ch01/ex19-reverse.c b/ch01/ex19-reverse.c new file mode 100644 index 0000000..7179290 --- /dev/null +++ b/ch01/ex19-reverse.c @@ -0,0 +1,56 @@ +#include <stdio.h> +#define MAXLINE 1000 /* maximum input line size */ + +int getln(char line[], int maxline); +void reverse(char to[], char from[], int len); + +/* reverse the input line */ +int main() +{ + int len; /* current line length */ + char line[MAXLINE]; /* current input line */ + char rline[MAXLINE]; /* reversed line */ + + while ((len = getln(line, MAXLINE)) > 0) { + reverse(rline, line, len); + printf("%s", rline); + } + + return 0; +} + +/* getln: read a line into s, return length */ +int getln(char s[], int lim) +{ + int c, i; + + for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + s[i] = '\0'; + return i; +} + +/* reverse: reverse the string */ +void reverse(char to[], char from[], int len) +{ + int i, nl = 0; + + if (from[len-1] == '\n') { + nl = 1; + --len; + } + + for (i=0; i < len; ++i) + to[i] = from[len-i-1]; + + if (nl == 1) { + to[i] = '\n'; + ++i; + } + + to[i] = '\0'; +} |
