20130313
[gdash.git] / include / file2c.cpp
blobaf692aa5c153b88d961aca58eac61adc1d6a610e
1 /*
2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
8 */
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
14 static void
15 usage(void)
18 fprintf(stderr, "usage: file2c [-n count] [-x] filename [prefix [suffix]]\n");
19 exit(1);
22 int
23 main(int argc, char *argv[])
25 int c, count, linepos, maxcount, radix;
26 FILE *fp;
28 maxcount = 0;
29 radix = 10;
30 while ((c = getopt(argc, argv, "n:x")) != -1) {
31 switch (c) {
32 case 'n': /* Max. number of bytes per line. */
33 maxcount = strtol(optarg, NULL, 10);
34 break;
35 case 'x': /* Print hexadecimal numbers. */
36 radix = 16;
37 break;
38 case '?':
39 default:
40 usage();
43 argc -= optind;
44 argv += optind;
46 if (argc == 0)
47 abort ();
48 fp = fopen(argv[0], "rb");
49 if (!fp)
50 abort ();
52 if (argc > 1)
53 printf("%s\n", argv[1]);
54 count = linepos = 0;
55 while((c = fgetc(fp)) != EOF) {
56 if (count) {
57 putchar(',');
58 linepos++;
60 if ((maxcount == 0 && linepos > 70) ||
61 (maxcount > 0 && count >= maxcount)) {
62 putchar('\n');
63 count = linepos = 0;
65 switch (radix) {
66 case 10:
67 linepos += printf("%d", c);
68 break;
69 case 16:
70 linepos += printf("0x%02x", c);
71 break;
72 default:
73 abort();
75 count++;
77 fclose (fp);
78 putchar('\n');
79 if (argc > 2)
80 printf("%s\n", argv[2]);
81 return (0);