diff options
Diffstat (limited to 'ch1/reverse.c')
-rw-r--r-- | ch1/reverse.c | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/ch1/reverse.c b/ch1/reverse.c new file mode 100644 index 0000000..98edd98 --- /dev/null +++ b/ch1/reverse.c @@ -0,0 +1,70 @@ +#include<stdio.h> + +#define MAXLENGTH 1000 + +// Prototypes +int get_line(char line[], int maxlength); +void line_copy(char to[], char from[]); +void reverse_copy(char to[], char from[], int length); + +/* + * MAIN + * Reverse all lines on STDIN. + */ +int main() { + int len; // current line length + char line[MAXLENGTH]; // current input line + char reversed_line[MAXLENGTH]; // current reversed line + + while ((len = get_line(line, MAXLENGTH)) > 0) { + reverse_copy(reversed_line, line, len); + printf("%s\n", reversed_line); + } + return 0; +} + +/* + * GET_LINE + * Read STDIN into LINE up to MAXLENGTH. + * Returns the length of LINE. + */ +int get_line(char line[], int maxlength) { + int c, i; + + for (i = 0; i < maxlength - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + if (c == '\n') { + line[i] = c; + ++i; + } + line[i] = '\0'; + return i; +} + +/* + * LINE_COPY + * Copy FROM into TO; assume TO is big enough. + */ +void line_copy(char to[], char from[]) { + int i; + + i = 0; + while ((to[i] = from[i]) != '\0') + ++i; +} + +/* + * REVERSE_COPY + * Copy FROM into TO (of length LENGTH) in reverse order; assume TO is big + * enough. + */ +void reverse_copy(char to[], char from[], int length) { + int i; + + for (i = 0; i < length; ++i) { + to[length - 1 - i] = from[i]; + } + + to[length] = '\0'; +} + |