Initial import of hexdump.c file
[eleutheria.git] / fileops / hexdump.c
blob2ec58f7244fc8f7d705785a46c77ed73f98ecccf
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 readbytes;
18 int caps, opt;
19 int totalbytes = 0;
20 char *fpath;
22 /* Parse arguments */
23 caps = 0;
24 len = -1;
25 skip = 0;
26 fpath = NULL;
27 while ((opt = getopt(argc, argv, "Cn:s:f:")) != -1) {
28 switch (opt) {
29 case 'C':
30 caps = 1;
31 break;
32 case 'n':
33 len = atoi(optarg);
34 break;
35 case 's':
36 skip = atoi(optarg);
37 break;
38 case 'f':
39 fpath = optarg;
40 break;
41 default: /* '?' */
42 dieu(argv[0]);
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("%08lX ", (unsigned long)cnt * BUFSIZE + skip);
75 for (i = 0; i < readbytes && (totalbytes < len || len == -1); i++, totalbytes++) {
76 printf("%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);