Page 155
Write a program that will print arbitrary input in a sensible way. As a minimum, it should print non-graphic characters in octal or hexadecimal according to local custom, and break long text lines.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MIN_CHAR ' '
#define MAX_CHAR '~'
#define WRAP_LEN 10
#define MAX_BUF 1000
int main()
{
int c;
char line_buf[MAX_BUF];
char *line_ptr = line_buf;
char word_buf[MAX_BUF];
char *word_ptr = word_buf;
while ((c = *word_ptr++ = getchar()) != EOF) {
if (isspace(c)) {
*word_ptr = '\0';
strcpy(line_ptr, word_buf);
line_ptr += word_ptr - word_buf;
word_ptr = word_buf;
} else if (c < MIN_CHAR || c > MAX_CHAR) {
--word_ptr;
word_ptr += sprintf(word_ptr, "0x%x", c);
}
if (c == '\n' ||
line_ptr - line_buf + word_ptr - word_buf > WRAP_LEN) {
if (line_ptr - line_buf > 0 && c != '\n') {
*line_ptr++ = '\n';
}
*line_ptr = '\0';
printf("%s", line_buf);
line_ptr = line_buf;
}
}
}