Skip to content

Commit

Permalink
Add solutionf of 1-22
Browse files Browse the repository at this point in the history
  • Loading branch information
kyrylo committed Apr 13, 2012
1 parent 51cb97e commit 1db3ffb
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions chapter_1/1-22/fold.c
@@ -0,0 +1,58 @@
/*
* 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.
*
* Date: April 13, 2012
*/

#include <stdio.h>

#define MAXLINE 1000
#define MAXLENGTH 10

int _getline(char line[], int maxline);

main()
{
int i, j, len, offset;
char line[MAXLINE];

while ((len = _getline(line, MAXLINE)) > 0) {
for (i = 0; i < len; ++i) {

if (i % MAXLENGTH == 0 && i != 0) {
j = 0;
offset = i;

while (offset > 0 && line[offset] != ' ' && line[offset] != '\t') {
++j;
offset = i - j;
}

if (offset != 0)
line[offset] = '\n';
}

}
printf("%s", line);
}
}

int _getline(char s[], int lim)
{
int c, i;

for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;

if (c == '\n') {
s[i] = c;
++i;
}

s[i] = '\0';

return i;
}

0 comments on commit 1db3ffb

Please sign in to comment.