xref: /dragonfly/usr.bin/file2c/file2c.c (revision 91dc43dd)
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  *
9  * $FreeBSD: src/usr.bin/file2c/file2c.c,v 1.11 2007/10/30 17:49:00 ru Exp $
10  * $DragonFly: src/usr.bin/file2c/file2c.c,v 1.4 2008/04/05 09:12:45 swildner Exp $
11  *
12  */
13 
14 #include <limits.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <unistd.h>
18 
19 static void
20 usage(void)
21 {
22 
23 	fprintf(stderr, "usage: %s [-sx] [-n count] [prefix [suffix]]\n",
24 	    getprogname());
25 	exit(1);
26 }
27 
28 int
29 main(int argc, char *argv[])
30 {
31 	int c, count, linepos, maxcount, pretty, radix;
32 
33 	maxcount = 0;
34 	pretty = 0;
35 	radix = 10;
36 	while ((c = getopt(argc, argv, "n:sx")) != -1) {
37 		switch (c) {
38 		case 'n':	/* Max. number of bytes per line. */
39 			maxcount = strtol(optarg, NULL, 10);
40 			break;
41 		case 's':	/* Be more style(9) compliant. */
42 			pretty = 1;
43 			break;
44 		case 'x':	/* Print hexadecimal numbers. */
45 			radix = 16;
46 			break;
47 		case '?':
48 		default:
49 			usage();
50 		}
51 	}
52 	argc -= optind;
53 	argv += optind;
54 
55 	if (argc > 0)
56 		printf("%s\n", argv[0]);
57 	count = linepos = 0;
58 	while((c = getchar()) != EOF) {
59 		if (count) {
60 			putchar(',');
61 			linepos++;
62 		}
63 		if ((maxcount == 0 && linepos > 70) ||
64 		    (maxcount > 0 && count >= maxcount)) {
65 			putchar('\n');
66 			count = linepos = 0;
67 		}
68 		if (pretty) {
69 			if (count) {
70 				putchar(' ');
71 				linepos++;
72 			} else {
73 				putchar('\t');
74 				linepos += 8;
75 			}
76 		}
77 		switch (radix) {
78 		case 10:
79 			linepos += printf("%d", c);
80 			break;
81 		case 16:
82 			linepos += printf("0x%02x", c);
83 			break;
84 		default:
85 			abort();
86 		}
87 		count++;
88 	}
89 	putchar('\n');
90 	if (argc > 1)
91 		printf("%s\n", argv[1]);
92 	return (0);
93 }
94