Page 34

Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the

#include <stdio.h>

#define WRAP_WIDTH 10
#define BUF_MAX 1000

void flush(int buf_pos);

char buffer[BUF_MAX + 1]; // + 1 to allow for null terminator
int written_len = 0;

int main()
{
	int c;

	extern int written_len;
	extern char buffer[];
	int buf_pos = 0;

	while ((c = getchar()) != EOF) {
		if (buf_pos < BUF_MAX) {
			buffer[buf_pos++] = c;

			if (c == ' ') {
				flush(buf_pos);
				buf_pos = 0;
			} else if (c == '\n') {
				flush(buf_pos);
				written_len = 0;
				buf_pos = 0;
			} else if ((written_len > 0) &&
				   (written_len + buf_pos > WRAP_WIDTH)) {
				putchar('\n');
				written_len = 0;
			}
		} else {
			printf("Buffer overflow!\n");
		}
	}
}

void flush(int buf_pos)
{
	extern char buffer[];
	extern int written_len;

	buffer[buf_pos] = '\0';
	printf("%s", buffer);

	written_len += buf_pos;
}