Implement -C option for capital hex letters
[eleutheria.git] / fileops / hexdump.c
blobb1d48f82b83b97f5319c77da2775f00e111d179c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> /* for memset() */
4 #include <getopt.h>
6 /* Function prototypes */
7 void diep(const char *s);
8 void dieu(const char *pname);
10 #define BUFSIZE 20 /* Must be dividable by 2 */
12 int main(int argc, char *argv[])
14 unsigned char buf[BUFSIZE + 1]; /* +1 for the '\0' */
15 FILE *fp;
16 int cnt, i, j, len, skip;
17 int caps, opt;
18 int readbytes, totalbytes = 0;
19 char *fpath;
21 /* Parse arguments */
22 caps = 0;
23 len = -1;
24 skip = 0;
25 fpath = NULL;
26 while ((opt = getopt(argc, argv, "Cn:s:f:")) != -1) {
27 switch (opt) {
28 case 'C':
29 caps = 1;
30 break;
31 case 'n':
32 len = atoi(optarg);
33 break;
34 case 's':
35 skip = atoi(optarg);
36 break;
37 case 'f':
38 fpath = optarg;
39 break;
40 default: /* '?' */
41 dieu(argv[0]);
45 /* optind shows to the argv[] index of the first non-option element */
46 if (optind < argc) {
47 fprintf(stderr, "non-option argv[]-elements: ");
48 while (optind < argc)
49 fprintf(stderr, "%s ", argv[optind++]);
50 fprintf(stderr, "\n");
51 exit(EXIT_FAILURE);
54 if (fpath == NULL)
55 dieu(argv[0]);
57 /* Open file */
58 if ((fp = fopen(fpath, "r")) == NULL)
59 diep("open");
61 /* Skip ``skip'' bytes */
62 fseek(fp, skip, SEEK_SET);
64 /* Loop */
65 cnt = 0;
66 while(!feof(fp) && (totalbytes < len || len == -1)) {
67 /* Initialize buffer */
68 memset(buf, 0, BUFSIZE);
70 /* Read ``BUFSIZE'' elements of 1 byte long from file */
71 readbytes = fread(buf, 1, BUFSIZE, fp);
73 /* Print buffer */
74 printf(caps == 1 ? "%08lX " : "%08lx ", (unsigned long)cnt * BUFSIZE + skip);
75 for (i = 0; i < readbytes && (totalbytes < len || len == -1); i++, totalbytes++) {
76 printf(caps == 1 ? "%02X " : "%02x ", buf[i]);
77 if (i == (BUFSIZE / 2) - 1)
78 printf(" ");
81 /* Fill in the blanks */
82 for (j = 0; j < (BUFSIZE - i); j++) {
83 printf(" ");
84 if (j == (BUFSIZE/2) - 1)
85 printf(" ");
89 * Print the output characters in the default character set.
90 * Nonprinting characters are displayed as a single ``.''
92 printf(" |");
93 for (j = 0; j < i; j++) {
94 if (buf[j] >= 32 && buf[j] <= 127)
95 printf("%c", buf[j]);
96 else
97 printf(".");
99 printf("|");
101 /* New line */
102 printf("\n");
104 cnt++;
107 /* Close device file */
108 (void)fclose(fp);
110 return EXIT_SUCCESS;
113 void diep(const char *s)
115 perror(s);
116 exit(EXIT_FAILURE);
119 void dieu(const char *pname)
121 fprintf(stderr, "Usage: %s [-C] [-n length] [-s skip] -f file\n", pname);
122 exit(EXIT_FAILURE);