Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created July 6, 2013 04:37
Show Gist options
  • Save EdgeCaseBerg/5938659 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/5938659 to your computer and use it in GitHub Desktop.
Exercise 1-22 from The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie​ "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…
#include <stdio.h>
/*
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.
*/
#define COLUMN_WIDTH 80
#define MAX_LINE 1000
main(){
char currentWord[MAX_LINE];
int i;
for (i = 0; i < MAX_LINE; ++i)
currentWord[i] = '\0';
int c,length,pos;
pos = 0;
length =0;
while((c = getchar()) != EOF){
if(c == ' ' || c =='\t' || c =='\n'){
//End buffered word
currentWord[pos] = '\0';
//Wrap word
if(length + pos >= COLUMN_WIDTH){
printf("\n");
length = pos;
}else{
if( c == '\n')
length=0;
if( c == '\t')
length = length + 4;
else
length++;
}
printf("%s",currentWord);
putchar(c);
pos = 0;
}else{
//Buffer word
currentWord[pos] =c;
++pos;
}
++length;
}
}
@EdgeCaseBerg
Copy link
Author

To run:

$cc wrap80.c -o wrap
$$./wrap < somefiletowrap.txt > formatedfile.txt

@dwest62
Copy link

dwest62 commented Aug 15, 2022

Several errors with test input

image
image
image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment