00001
00002
00003
00004
00005
00006
00007
00008 #define _POSIX_C_SOURCE 2
00009
00010 #include <errno.h>
00011 #include <stdarg.h>
00012 #include <stdio.h>
00013 #include <stdlib.h>
00014 #include <string.h>
00015 #include <unistd.h>
00016
00017 char *progname;
00018 unsigned char buf[1024];
00019
00020 static void fatal(char *fmt, ...);
00021 static void usage(void);
00022
00023 int main(int argc, char *argv[])
00024 {
00025 int c, i, r, first;
00026 FILE *file_in, *file_out;
00027 char *in_name;
00028 char *o_arg;
00029
00030 (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]);
00031
00032 o_arg= NULL;
00033 while (c= getopt(argc, argv, "?o:"), c != -1)
00034 {
00035 switch(c)
00036 {
00037 case '?': usage();
00038 case 'o': o_arg= optarg; break;
00039 default: fatal("getopt failed: '%c'\n", c);
00040 }
00041 }
00042
00043 if (o_arg)
00044 {
00045 file_out= fopen(o_arg, "w");
00046 if (file_out == NULL)
00047 {
00048 fatal("unable to create '%s': %s\n",
00049 o_arg, strerror(errno));
00050 exit(1);
00051 }
00052 }
00053 else
00054 file_out= stdout;
00055
00056 if (optind < argc)
00057 {
00058 in_name= argv[optind];
00059 optind++;
00060 file_in= fopen(in_name, "r");
00061 if (file_in == NULL)
00062 {
00063 fatal("unable to open '%s': %s",
00064 in_name, strerror(errno));
00065 }
00066 }
00067 else
00068 {
00069 in_name= "(stdin)";
00070 file_in= stdin;
00071 }
00072
00073 if (optind != argc)
00074 usage();
00075
00076 first= 1;
00077 for (;;)
00078 {
00079 r= fread(buf, 1, sizeof(buf), file_in);
00080 if (r == 0)
00081 break;
00082 for (i= 0; i<r; i++)
00083 {
00084 if ((i % 8) == 0)
00085 {
00086 if (first)
00087 {
00088 fprintf(file_out, "\t");
00089 first= 0;
00090 }
00091 else
00092 fprintf(file_out, ",\n\t");
00093 }
00094 else
00095 fprintf(file_out, ", ");
00096 fprintf(file_out, "0x%02x", buf[i]);
00097 }
00098 }
00099
00100 if (ferror(file_in))
00101 {
00102 fatal("read error on %s: %s\n",
00103 in_name, strerror(errno));
00104 }
00105 fprintf(file_out, "\n");
00106
00107 exit(0);
00108 }
00109
00110 static void fatal(char *fmt, ...)
00111 {
00112 va_list ap;
00113
00114 fprintf(stderr, "%s: ", progname);
00115
00116 va_start(ap, fmt);
00117 vfprintf(stderr, fmt, ap);
00118 va_end(ap);
00119
00120 fprintf(stderr, "\n");
00121
00122 exit(1);
00123 }
00124
00125 static void usage(void)
00126 {
00127 fprintf(stderr, "Usage: bintoc [-o <out-file>] [<in-file>]\n");
00128 exit(1);
00129 }