diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/linebuffer.c | 6 | ||||
| -rw-r--r-- | src/main.c | 22 |
2 files changed, 17 insertions, 11 deletions
diff --git a/src/linebuffer.c b/src/linebuffer.c index 1b9c1f1..7c2fac3 100644 --- a/src/linebuffer.c +++ b/src/linebuffer.c @@ -1,5 +1,6 @@ #include "linebuffer.h" +#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -26,6 +27,7 @@ void linebuffer_destroy(LineBuffer *lb) { } void linebuffer_clear(LineBuffer *lb) { + memset(lb->_buffer, 0, lb->_buffer_length + 1); lb->_num_words = 0; lb->_buffer_length = 0; } @@ -59,8 +61,8 @@ int linebuffer_write_justified(LineBuffer *lb, FILE *fp) { size_t spaces_to_insert = 0; for (size_t i = 0; i < lb->_buffer_length; i++) { - if (lb->_buffer[i] != ' ') { - return_code = fputs(&lb->_buffer[i], fp); + if (!isspace(lb->_buffer[i])) { + return_code = fputc(lb->_buffer[i], fp); if (return_code == EOF) { return EOF; } @@ -6,31 +6,35 @@ #include "word.h" #define MAX_WORD_LENGTH 20 +#define LINEBUFFER_CAPACITY 60 int main(void) { char word[MAX_WORD_LENGTH + 2]; size_t word_length; - int err; - LineBuffer *lb = linebuffer_create(40); + int read_word_result; + LineBuffer *lb = linebuffer_create(LINEBUFFER_CAPACITY); - while (true) { - err = read_word(stdin, word, MAX_WORD_LENGTH + 1); - if (err == EOF) { - printf("Error reading word\n"); - return 1; - } + while ((read_word_result = read_word(stdin, word, MAX_WORD_LENGTH + 1)) == + READ_WORD_SUCCESS) { word_length = strlen(word); if (word_length == 0) { linebuffer_write(lb, stdout); + linebuffer_destroy(lb); return 0; } if (word_length > MAX_WORD_LENGTH) { word[MAX_WORD_LENGTH] = '*'; } - if (word_length + 1 > linebuffer_space_remaining(lb)) { + if (word_length >= linebuffer_space_remaining(lb)) { linebuffer_write_justified(lb, stdout); linebuffer_clear(lb); } linebuffer_append_word(lb, word); + memset(word, 0, MAX_WORD_LENGTH + 2); + } + if (read_word_result == READ_WORD_ERR_READ) { + printf("Error reading word\n"); + return 1; } + return 0; } |