Check stdin for binary too

This commit is contained in:
Shav Kinderlehrer 2023-04-19 13:28:06 -04:00
parent 219075499f
commit c713312b22
3 changed files with 25 additions and 17 deletions

View File

@ -2,7 +2,7 @@
#define ARG_H #define ARG_H
#include <stdbool.h> #include <stdbool.h>
#define LAT_VERSION "0.10.1" #define LAT_VERSION "0.10.2"
struct config { struct config {
bool stdin; bool stdin;

View File

@ -5,6 +5,23 @@
#include "types.h" #include "types.h"
#include "util.h" #include "util.h"
bool isbinary(struct filedata *f) {
// guess if printable
// from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs
int testlen = f->buflen >= 64 ? 64 : f->buflen;
char *testbuf[testlen];
memcpy(testbuf, f->buf, testlen);
char *result = memchr(testbuf, 0x00, testlen);
if (result) {
return true;
} else {
return false;
}
}
struct filedata readfile(FILE *fp, bool isstdin) { struct filedata readfile(FILE *fp, bool isstdin) {
struct filedata f; struct filedata f;
@ -44,6 +61,8 @@ struct filedata readfile(FILE *fp, bool isstdin) {
} }
f.buf[f.buflen] = '\0'; f.buf[f.buflen] = '\0';
f.binary = isbinary(&f);
return f; return f;
} }
@ -60,19 +79,7 @@ struct filedata readfile(FILE *fp, bool isstdin) {
die("fread"); die("fread");
} }
// guess if printable f.binary = isbinary(&f);
// from https://github.com/sharkdp/content_inspector/blob/master/src/lib.rs
int testlen = f.buflen >= 64 ? 64 : f.buflen;
char *testbuf[testlen];
memcpy(testbuf, f.buf, testlen);
char *result = memchr(testbuf, 0x00, testlen);
if (result) {
f.binary = 1;
} else {
f.binary = 0;
}
return f; return f;
} }

View File

@ -42,11 +42,11 @@ void run(FILE *fp, char *filename, bool tty) {
if (conf.headers) { if (conf.headers) {
char *addon = f.binary ? "<binary>" : ""; char *addon = f.binary ? "<binary>" : "";
if (!conf.pager) if (conf.pager)
fprintf(err, "%s%s%s%s\r\n", invert_t, basename(filename), addon, reset);
else
fprintf(err, "\x1b[2K\r%s%s%s%s\r\n", invert_t, basename(filename), addon, fprintf(err, "\x1b[2K\r%s%s%s%s\r\n", invert_t, basename(filename), addon,
reset); reset);
else
fprintf(err, "%s%s%s%s\r\n", invert_t, basename(filename), addon, reset);
} }
conf.process = (tty && !f.binary); conf.process = (tty && !f.binary);
@ -147,6 +147,7 @@ int main(int argc, char *argv[]) {
run(fp, argv[i], tty); run(fp, argv[i], tty);
fclose(fp); fclose(fp);
if (tty && (i + 1 != argc)) { if (tty && (i + 1 != argc)) {
printf("offset: %d argc: %d\n", i, argc);
fprintf(err, "\r\n"); // separate concurrent files in tty fprintf(err, "\r\n"); // separate concurrent files in tty
} }
} }