Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Exercise 1-22.
- * Write a program to ``fold'' long input lines into two or more shorter lines
- * after the last non-blank character that occurs before the n-th column of
- * input. Make sure your program does something intelligent with very long
- * lines, and if there are no blanks or tabs before the specified column.
- */
- # include <stdio.h>
- #define TABSTOP 8
- #define LINESIZE 20
- #define WORDSIZE (3 * LINESIZE)
- int
- get_word(char *word, int lim) {
- int len = 0;
- int c;
- while (len < lim - 1 && (c = getchar()) != EOF) {
- if (c == ' ' || c == '\n' || c == '\t') {
- word[len++] = c;
- word[len] = '\0';
- return len;
- }
- word[len++] = c;
- }
- word[len] = '\0';
- return len;
- }
- int
- main() {
- char word[WORDSIZE];
- int len;
- int offset = 0;
- int last;
- int i;
- int complete;
- while ((len = get_word(word, WORDSIZE)) != 0) {
- last = word[len - 1];
- /* can we just print the whole word in the current line*/
- if (offset + len <= LINESIZE - 1) {
- printf("%s",word);
- offset +=len;
- /* reset offset if it ends with '\n' */
- if (word[len - 1] == '\n') {
- offset = 0;
- }
- } else {
- /* shall we start new line now */
- if (LINESIZE - offset <= 1 ) {
- putchar ('\n');
- offset = 0;
- }
- /* print the word */
- for (i = 0; i < len; i++) {
- /*
- * when we are close to the end of th line and there are still
- * few characters left, then we have no option but to hyphenate
- * the word
- */
- if (offset == LINESIZE - 2 && (len -i -1) > 2) {
- putchar('-');
- putchar('\n');
- offset = 0;
- }
- putchar(word[i]);
- offset++;
- }
- /* if the word ends with '\n', then reset offset */
- if (word[i - 1] == '\n') {
- offset = 0;
- }
- }
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment