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