Skip to content

Instantly share code, notes, and snippets.

@sandagolcea
Created June 27, 2013 03:03
Show Gist options
  • Select an option

  • Save sandagolcea/5873642 to your computer and use it in GitHub Desktop.

Select an option

Save sandagolcea/5873642 to your computer and use it in GitHub Desktop.
fold line program : takes lines from the stdin until EOF (ctrl+D), and folds them on more rows, just like in word.
#include <stdio.h>
#define MAXLINE 400
#define FOLDLINE 40
int getline(char line[MAXLINE]){
int i=0, c;
while ((c=getchar()) != EOF && c!= '\n'){
line[i++]=c;
}
if (c=='\n') line[i++]=c;
line[i]='\0';
return i;
}
int foldLine(char line[], int length){
int index=0, j=0;
if (length<=FOLDLINE+1) {
printf("%s", line);
return 0;
}
while (j<=length){
//the next 40(e.g.) chars
index=j+FOLDLINE;
//if the chars left in line are less that 40(e.g.), print what's left, ret
if(index>length) {
while (j<=length){
printf("%c",line[j]);
j++;
}
return 0;
}
//printf("\nj=%d",j);
//go back until you have reached the first white character
while ((index > j ) && (line[index] != ' ') && (line[index] != '\t') ) {
index--;
//printf(" %d", index);
}
if(index<=j)
for (int k=j; k<(j+FOLDLINE); k++) {
printf("%c", line[k]);
}
else
//print from the start to the last white character found front->back
for (int k=j; k < index; k++){
printf("%c",line[k]);
}
printf("\n");
if (index<=j) index=index+FOLDLINE-1;
j=index+1;
}
}
int main(){
int length=0;
char line[MAXLINE];
while ((length=getline(line)) > 0){
foldLine(line, length);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment