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