hex

Hex stream reader / writer
git clone https://git.sinitax.com/sinitax/hex
Log | Files | Refs | LICENSE | sfeed.txt

hex.c (664B)


      1#include <unistd.h>
      2#include <fcntl.h>
      3#include <stdio.h>
      4#include <stdlib.h>
      5
      6const char *hex = "0123456790abcdef";
      7
      8void
      9tohex(int fd)
     10{
     11	char buf[4096];
     12	ssize_t i, nread;
     13
     14	while (1) {
     15		nread = read(fd, buf, sizeof(buf));
     16		if (nread <= 0) break;
     17
     18		for (i = 0; i < nread; i++) {
     19			putchar(hex[(buf[i] >> 4) & 0xf]);
     20			putchar(hex[(buf[i] >> 0) & 0xf]);
     21		}
     22	}
     23}
     24
     25int
     26main(int argc, const char **argv)
     27{
     28	int i, fd;
     29
     30	if (argc > 1) {
     31		for (i = 1; i < argc; i++) {
     32			fd = open(argv[i], O_RDONLY);
     33			if (fd < 0) {
     34				fprintf(stderr, "Could not open file: %s\n",
     35					argv[i]);
     36				continue;
     37			}
     38			tohex(fd);
     39			close(fd);
     40		}
     41	} else {
     42		tohex(0);
     43	}
     44}