source: trunk/minix/drivers/memory/ramdisk/bintoc.c@ 15

Last change on this file since 15 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 1.9 KB
RevLine 
[9]1/*
2bintoc.c
3
4Convert a (binary) file to a series of comma separated hex values suitable
5for initializing a character array in C.
6*/
7
8#define _POSIX_C_SOURCE 2
9
10#include <errno.h>
11#include <stdarg.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15#include <unistd.h>
16
17char *progname;
18unsigned char buf[1024];
19
20static void fatal(char *fmt, ...);
21static void usage(void);
22
23int main(int argc, char *argv[])
24{
25 int c, i, r, first;
26 FILE *file_in, *file_out;
27 char *in_name;
28 char *o_arg;
29
30 (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]);
31
32 o_arg= NULL;
33 while (c= getopt(argc, argv, "?o:"), c != -1)
34 {
35 switch(c)
36 {
37 case '?': usage();
38 case 'o': o_arg= optarg; break;
39 default: fatal("getopt failed: '%c'\n", c);
40 }
41 }
42
43 if (o_arg)
44 {
45 file_out= fopen(o_arg, "w");
46 if (file_out == NULL)
47 {
48 fatal("unable to create '%s': %s\n",
49 o_arg, strerror(errno));
50 exit(1);
51 }
52 }
53 else
54 file_out= stdout;
55
56 if (optind < argc)
57 {
58 in_name= argv[optind];
59 optind++;
60 file_in= fopen(in_name, "r");
61 if (file_in == NULL)
62 {
63 fatal("unable to open '%s': %s",
64 in_name, strerror(errno));
65 }
66 }
67 else
68 {
69 in_name= "(stdin)";
70 file_in= stdin;
71 }
72
73 if (optind != argc)
74 usage();
75
76 first= 1;
77 for (;;)
78 {
79 r= fread(buf, 1, sizeof(buf), file_in);
80 if (r == 0)
81 break;
82 for (i= 0; i<r; i++)
83 {
84 if ((i % 8) == 0)
85 {
86 if (first)
87 {
88 fprintf(file_out, "\t");
89 first= 0;
90 }
91 else
92 fprintf(file_out, ",\n\t");
93 }
94 else
95 fprintf(file_out, ", ");
96 fprintf(file_out, "0x%02x", buf[i]);
97 }
98 }
99
100 if (ferror(file_in))
101 {
102 fatal("read error on %s: %s\n",
103 in_name, strerror(errno));
104 }
105 fprintf(file_out, "\n");
106
107 exit(0);
108}
109
110static void fatal(char *fmt, ...)
111{
112 va_list ap;
113
114 fprintf(stderr, "%s: ", progname);
115
116 va_start(ap, fmt);
117 vfprintf(stderr, fmt, ap);
118 va_end(ap);
119
120 fprintf(stderr, "\n");
121
122 exit(1);
123}
124
125static void usage(void)
126{
127 fprintf(stderr, "Usage: bintoc [-o <out-file>] [<in-file>]\n");
128 exit(1);
129}
Note: See TracBrowser for help on using the repository browser.