Skip to contentSkip to conversation

more: avoid libmagic telling an empty file is binary

PATCH Applied Sami Kerola 2 participants 2 messages May 25, 2020 Util-Linux package

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 more: avoid libmagic telling an empty file is binary

My earlier change that took libmagic in use to identify mime-type of an input file caused empty files to be marked binary. Before the change empty files were simply displayed as empty. This change will restore that behavior.

Addresses: 09070e1a658e70ec203150e4fa5f486b32771858

---
 text-utils/more.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
text-utils/more.c +17 -1
index b69fa5c5b..3855d8549 100644
@@ -395,7 +395,23 @@ static void print_separator(const int c, int n)
 static int check_magic(struct more_control *ctl, char *fs)
 {
 #ifdef HAVE_MAGIC
-	const char *mime_encoding = magic_descriptor(ctl->magic, fileno(ctl->current_file));
+	const int fd = fileno(ctl->current_file);
+	const char *mime_encoding = magic_descriptor(ctl->magic, fd);
+	const char *magic_error_msg = magic_error(ctl->magic);
+	struct stat st;
+
+	if (magic_error_msg) {
+		printf(_("magic failed: %s\n"), magic_error_msg);
+		return 0;
+	}
+	if (fstat(fd, &st)) {
+		warn(_("cannot stat %s"), fs);
+		return 1;
+	}
+	if (st.st_size == 0) {
+		/* libmagic tells an empty file has binary encoding */
+		return 0;
+	}
 
 	if (!mime_encoding || !(strcmp("binary", mime_encoding))) {
 		printf(_("\n******** %s: Not a text file ********\n\n"), fs);
Signature · 1 line
2.26.2
maintainer Applied
#1 lore raw
Quoted 2 lines · Sami Kerola
 text-utils/more.c | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)

Applied, thanks.

Signature · 2 lines
 Karel Zak  <[email protected]>
 http://karelzak.blogspot.com