From 3ce6dbf9b9958b44acb1e545fe4fead4aefaf90a Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Tue, 14 May 2019 15:41:19 -0400 Subject: Started reverse --- no_trailers.c | 2 +- reverse.c | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 reverse.c diff --git a/no_trailers.c b/no_trailers.c index e600e35..80dbc0f 100644 --- a/no_trailers.c +++ b/no_trailers.c @@ -8,7 +8,7 @@ void copy(char to[], char from[]); /* * MAIN - * Prints longest line in STDIN. + * Removes all trailing whitespace and blank lines from STDIN. */ int main() { int len; // current line length diff --git a/reverse.c b/reverse.c new file mode 100644 index 0000000..0681560 --- /dev/null +++ b/reverse.c @@ -0,0 +1,68 @@ +#include + +#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[]); + +/* + * 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(line, reversed_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; + + i = 0; + while ((to[i] = from[i]) != '\0') + ++i; +} + -- cgit v1.2.3