From abc023764a4fccdfa0606692a381d543ae003f25 Mon Sep 17 00:00:00 2001 From: Konstantine Tsafatinos Date: Thu, 16 Nov 2023 16:20:15 -0500 Subject: [PATCH] add ex1_22, folds --- intro/ex1_22_fold.c | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 intro/ex1_22_fold.c diff --git a/intro/ex1_22_fold.c b/intro/ex1_22_fold.c new file mode 100644 index 0000000..52017a3 --- /dev/null +++ b/intro/ex1_22_fold.c @@ -0,0 +1,55 @@ +#include + +#define MAXLINE 1000 /* maximum characters in a line */ +#define FOLDLENGTH 20 /* sub line size */ + +int my_getline(char line[], int maxline); +void fold(char input[], int maxline, int foldlength); + + +int main() +{ + int len; /* current line length */ + char line[MAXLINE]; /* current input line */ + + while ((len = my_getline(line, MAXLINE)) > 0) { + fold(line, MAXLINE, FOLDLENGTH); + } + return 0; +} + +/* my_getline: reads in a line, return the length */ +int my_getline(char line[], int lim) +{ + int c, i; + + for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + if (c == '\n') { + line[i] = c; + ++i; + } + line[i] = '\0'; + return i; +} + +/* fold: split long input lines into 2 or more shorter lines after + the last non-blank character that occurs before the nth + column of input. */ +void fold(char input[], int lim, int fold_lim) +{ + int i, j; + char fold_line[lim]; + + j = 0; + for (i = 0; i < lim-1 && input[i] != '\0'; ++i, ++j) { + if (j > fold_lim-1 && input[i] != ' ' && input[i] != '\t') { + fold_line[j] = '\0'; + j = 0; + printf("%s\n", fold_line); + } + fold_line[j] = input[i]; + } + fold_line[j] = '\0'; + printf("%s\n", fold_line); +}