Path: blob/master/languages/cprogs/Ex_1.22_fold.c
1240 views
/* Exercise 1-22: Write a program to "fold" long input lines into two or more1shorter lines after the last non-blank character that occurs2before the n-th column of input. */34#include <stdio.h>567#define MAXCOL 35 /* folded line length */8#define TABVAL 8 /* standard tab length */9#define CURTAB(c) (TABVAL - ((c) % TABVAL)) /* current tab size */10#define NO_BLANK -1 /* signifies no blank found */1112int lastblank(const char arr[], int len);1314/* folds long input lines into two or more shorter lines */15int main(void)16{17int c; /* character variable */18int i, j; /* indexing variable(s) */19int pos; /* current position in array */20int col; /* current column of output */21int lbc; /* last blank character position */22char line[MAXCOL + 1]; /* fold array */2324pos = col = 0;25while ((c = getchar()) != EOF) {26/* process line array, keep track of line length by columns */27line[pos++] = c;28col += (c == '\t') ? CURTAB(col) : 1;2930/* create fold */31if (col >= MAXCOL || c == '\n') {32line[pos] = '\0';3334if ((lbc = lastblank(line, pos)) == NO_BLANK) {35/* split word if no blank characters */36for (i = 0; i < pos; ++i)37putchar(line[i]);38/* reset column value and array position */39col = pos = 0;40}41else {42/* print array up until last blank character */43for (i = 0; i < lbc; ++i)44putchar(line[i]);45/* feed remaining characters into buffer */46for (i = 0, j = lbc + 1, col = 0; j < pos; ++i, ++j) {47line[i] = line[j];48/* set new column value */49col += (c == '\t') ? CURTAB(col) : 1;50}51/* set array position after remaining characters */52pos = i;53}54/* finish folded line with newline character */55putchar('\n');56}57}5859return 0;60}6162/* finds the last whitespace character in an array63and returns the position */64int lastblank(const char arr[], int len)65{66int i, lbc;6768lbc = -1;69for (i = 0; i < len; ++i)70if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n')71lbc = i;7273return lbc;74}757677