sbase/fold.c
FRIGN 0545d32ce9 Handle '-' consistently
In general, POSIX does not define /dev/std{in, out, err} because it
does not want to depend on the dev-filesystem.
For utilities, it thus introduced the '-'-keyword to denote standard
input (and output in some cases) and the programs have to deal with
it accordingly.

Sadly, the design of many tools doesn't allow strict shell-redirections
and many scripts don't even use this feature when possible.

Thus, we made the decision to implement it consistently across all
tools where it makes sense (namely those which read files).

Along the way, I spotted some behavioural bugs in libutil/crypt.c and
others where it was forgotten to fshut the files after use.
2015-05-16 13:34:00 +01:00

114 lines
1.9 KiB
C

/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
static int bflag = 0;
static int sflag = 0;
static size_t width = 80;
static void
foldline(const char *str) {
const char *p, *spacesect = NULL;
size_t col, off;
for (p = str, col = 0; *p && *p != '\n'; p++) {
if (!UTF8_POINT(*p) && !bflag)
continue;
if (col >= width) {
off = (sflag && spacesect) ? spacesect - str : p - str;
if (fwrite(str, 1, off, stdout) != off)
eprintf("fwrite <stdout>:");
putchar('\n');
spacesect = NULL;
col = 0;
p = str += off;
}
if (sflag && isspace(*p))
spacesect = p + 1;
if (!bflag && iscntrl(*p)) {
switch(*p) {
case '\b':
col -= (col > 0);
break;
case '\r':
col = 0;
break;
case '\t':
col += (col + 1) % 8;
break;
}
} else {
col++;
}
}
fputs(str, stdout);
}
static void
fold(FILE *fp, const char *fname)
{
char *buf = NULL;
size_t size = 0;
while (getline(&buf, &size, fp) > 0)
foldline(buf);
if (ferror(fp))
eprintf("getline %s:", fname);
free(buf);
}
static void
usage(void)
{
eprintf("usage: %s [-bs] [-w num | -num] [FILE ...]\n", argv0);
}
int
main(int argc, char *argv[])
{
FILE *fp;
int ret = 0;
ARGBEGIN {
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case 'w':
width = estrtonum(EARGF(usage()), 1, MIN(LLONG_MAX, SIZE_MAX));
break;
ARGNUM:
width = ARGNUMF();
break;
default:
usage();
} ARGEND;
if (!argc) {
fold(stdin, "<stdin>");
} else {
for (; *argv; argc--, argv++) {
if ((*argv)[0] == '-' && !(*argv)[1]) {
*argv = "<stdin>";
fp = stdin;
} else if (!(fp = fopen(*argv, "r"))) {
weprintf("fopen %s:", *argv);
ret = 1;
continue;
}
fold(fp, *argv);
if (fp != stdin && fshut(fp, *argv))
ret = 1;
}
}
return !!(fshut(stdin, "<stdin>") + fshut(stdout, "<stdout>")) || ret;
}