Created
August 20, 2024 04:21
-
-
Save leptos-null/beb0b646636c35e1379a9909285e6610 to your computer and use it in GitHub Desktop.
Check input for non-print bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Leptos on 12/25/19. | |
// Copyright © 2019 Leptos. All rights reserved. | |
// | |
#import <stdio.h> | |
#import <fcntl.h> | |
#import <unistd.h> | |
#import <ctype.h> | |
static int checkFileDescriptor(const int fileDescriptor, const char *const path) { | |
char buff[0x200]; // this buffer size is fairly arbitrary | |
unsigned lineNumber = 1; | |
unsigned columnNumber = 1; | |
ssize_t readResult = 0; | |
do { | |
readResult = read(fileDescriptor, buff, sizeof(buff)); | |
if (readResult < 0) { | |
return -1; | |
} | |
for (ssize_t i = 0; i < readResult; i++) { | |
const char chr = buff[i]; | |
if (chr == '\n') { | |
lineNumber++; | |
columnNumber = 0; | |
} else if (!(isprint(chr) || chr == '\t')) { | |
printf("%s:%u:%u non-print: 0x%02hhx\n", path, lineNumber, columnNumber, chr); | |
} | |
columnNumber++; | |
} | |
} while (readResult > 0); | |
return 0; | |
} | |
int main(int argc, const char *argv[]) { | |
if (!isatty(STDIN_FILENO)) { | |
const char *const path = "<stdin>"; | |
if (checkFileDescriptor(STDIN_FILENO, path) != 0) { | |
perror(path); | |
} | |
} | |
for (int argi = 1; argi < argc; argi++) { | |
const char *const path = argv[argi]; | |
const int fileDescriptor = open(path, O_RDONLY); | |
if (fileDescriptor < 0) { | |
perror(path); | |
continue; | |
} | |
const int checkStatus = checkFileDescriptor(fileDescriptor, path); | |
if (checkStatus != 0) { | |
perror(path); | |
// no `continue` here because we still want to `close` the file | |
} | |
const int closeStatus = close(fileDescriptor); | |
if (closeStatus != 0) { | |
perror(path); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment