sbase/fold.c

114 lines
1.7 KiB
C
Raw Normal View History

2011-06-08 20:30:33 +00:00
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
2011-06-08 20:30:33 +00:00
#include "text.h"
#include "util.h"
2011-06-21 04:05:37 +00:00
static void fold(FILE *, long);
2011-06-08 20:30:33 +00:00
static void foldline(const char *, long);
static int bflag = 0;
static int sflag = 0;
2011-06-08 20:30:33 +00:00
2013-06-14 18:20:47 +00:00
static void
usage(void)
{
eprintf("usage: %s [-bs] [-w width] [FILE...]\n", argv0);
}
2011-06-08 20:30:33 +00:00
int
main(int argc, char *argv[])
{
long width = 80;
FILE *fp;
2013-06-14 18:20:47 +00:00
ARGBEGIN {
case 'b':
bflag = 1;
2013-06-14 18:20:47 +00:00
break;
case 's':
sflag = 1;
2013-06-14 18:20:47 +00:00
break;
case 'w':
width = estrtol(EARGF(usage()), 0);
break;
ARGNUM:
width = ARGNUMF(0);
break;
2013-06-14 18:20:47 +00:00
default:
usage();
} ARGEND;
if (argc == 0) {
2011-06-21 04:05:37 +00:00
fold(stdin, width);
2014-04-22 10:43:01 +00:00
} else {
for (; argc > 0; argc--, argv++) {
if (!(fp = fopen(argv[0], "r"))) {
2014-04-22 10:43:01 +00:00
weprintf("fopen %s:", argv[0]);
continue;
}
fold(fp, width);
fclose(fp);
}
2011-06-08 20:30:33 +00:00
}
2013-06-14 18:20:47 +00:00
2014-10-02 22:46:04 +00:00
return 0;
2011-06-08 20:30:33 +00:00
}
static void
2011-06-21 04:05:37 +00:00
fold(FILE *fp, long width)
2011-06-08 20:30:33 +00:00
{
char *buf = NULL;
size_t size = 0;
2014-11-18 20:49:30 +00:00
while (getline(&buf, &size, fp) != -1)
2011-06-08 20:30:33 +00:00
foldline(buf, width);
free(buf);
}
static void
2011-06-08 20:30:33 +00:00
foldline(const char *str, long width)
{
int space;
2011-06-21 04:05:37 +00:00
long col, j;
size_t i = 0, n = 0;
int c;
2011-06-08 20:30:33 +00:00
2011-06-10 03:22:59 +00:00
do {
space = 0;
for (j = i, col = 0; str[j] && col <= width; j++) {
c = str[j];
if (!UTF8_POINT(c) && !bflag)
2011-06-08 20:30:33 +00:00
continue;
if (sflag && isspace(c)) {
space = 1;
2011-06-08 20:30:33 +00:00
n = j+1;
}
else if (!space)
2011-06-08 20:30:33 +00:00
n = j;
if (!bflag && iscntrl(c))
switch(c) {
2011-06-08 20:30:33 +00:00
case '\b':
col--;
break;
case '\r':
col = 0;
break;
case '\t':
col += (col+1) % 8;
break;
}
else
col++;
}
if (fwrite(&str[i], 1, n-i, stdout) != n-i)
2011-06-08 20:30:33 +00:00
eprintf("<stdout>: write error:");
if (str[n])
2011-06-08 20:30:33 +00:00
putchar('\n');
} while (str[i = n] && str[i] != '\n');
2011-06-08 20:30:33 +00:00
}