#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1990, 1993\n\
The Regents of the University of California. All rights reserved.\n");
#endif
#ifndef lint
#if 0
static char sccsid[] = "@(#)fold.c 8.1 (Berkeley) 6/6/93";
#endif
__RCSID("$NetBSD: fold.c,v 1.8 1997/10/20 10:20:52 mrg Exp $");
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#define DEFLINEWIDTH 80
int main __P((int, char **));
static void fold __P((int));
static int new_column_position __P((int, int));
int count_bytes = 0;
int split_words = 0;
int
main(argc, argv)
int argc;
char **argv;
{
int ch;
int width;
char *p;
width = -1;
while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1)
switch (ch) {
case 'b':
count_bytes = 1;
break;
case 's':
split_words = 1;
break;
case 'w':
if ((width = atoi(optarg)) <= 0) {
(void)fprintf(stderr,
"fold: illegal width value.\n");
exit(1);
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if (width == -1) {
p = argv[optind - 1];
if (p[0] == '-' && p[1] == ch && !p[2])
width = atoi(++p);
else
width = atoi(argv[optind] + 1);
}
break;
default:
(void)fprintf(stderr,
"usage: fold [-bs] [-w width] [file ...]\n");
exit(1);
}
argv += optind;
argc -= optind;
if (width == -1)
width = DEFLINEWIDTH;
if (!*argv)
fold(width);
else for (; *argv; ++argv)
if (!freopen(*argv, "r", stdin)) {
err (1, "%s", *argv);
} else
fold(width);
exit(0);
}
static void
fold(width)
int width;
{
static char *buf = NULL;
static int buf_max = 0;
int ch, col;
int indx;
col = indx = 0;
while ((ch = getchar()) != EOF) {
if (ch == '\n') {
if (indx != 0)
fwrite (buf, 1, indx, stdout);
putchar('\n');
col = indx = 0;
continue;
}
col = new_column_position (col, ch);
if (col > width) {
int i, last_space;
#ifdef __GNUC__
last_space = 0;
#endif
if (split_words) {
for (i = 0, last_space = -1; i < indx; i++)
if (buf[i] == ' ')
last_space = i;
}
if (split_words && last_space != -1) {
last_space++;
fwrite (buf, 1, last_space, stdout);
memmove (buf, buf+last_space, indx-last_space);
indx -= last_space;
col = 0;
for (i = 0; i < indx; i++) {
col = new_column_position (col, ch);
}
} else {
fwrite (buf, 1, indx, stdout);
col = indx = 0;
}
putchar('\n');
col = new_column_position (col, ch);
}
if (indx + 1 > buf_max) {
buf_max += 2048;
if((buf = realloc (buf, buf_max)) == NULL) {
err (1, "realloc");
}
}
buf[indx++] = ch;
}
if (indx != 0)
fwrite (buf, 1, indx, stdout);
}
static int
new_column_position (col, ch)
int col;
int ch;
{
if (!count_bytes) {
switch (ch) {
case '\b':
if (col > 0)
--col;
break;
case '\r':
col = 0;
break;
case '\t':
col = (col + 8) & ~7;
break;
default:
++col;
break;
}
} else {
++col;
}
return col;
}