summaryrefslogtreecommitdiff
path: root/scripts/cquote.c
blob: 0363574d02280d2a1d75453874573b2cd70a974f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/* cquote.c -- Turn the contents of a file into a quoted string */

#include <stdio.h>
#include <string.h>

/* We never want to build memento versions of the cquote util */
#undef MEMENTO

static void
clean(char *p)
{
	while (*p)
	{
		if ((*p == '/') || (*p == '.') || (*p == '\\') || (*p == '-'))
			*p = '_';
		p ++;
	}
}

int
main(int argc, char **argv)
{
	FILE *fi, *fo;
	char name[256];
	char *realname;
	int i, c;

	if (argc < 3)
	{
		fprintf(stderr, "usage: cquote output.c lots of text files\n");
		return 1;
	}

	fo = fopen(argv[1], "wb");
	if (!fo)
	{
		fprintf(stderr, "cquote: could not open output file '%s'\n", argv[1]);
		return 1;
	}

	fprintf(fo, "/* This is an automatically generated file. Do not edit. */\n");

	for (i = 2; i < argc; i++)
	{
		realname = strrchr(argv[i], '/');
		if (!realname)
			realname = strrchr(argv[i], '\\');
		if (realname)
			realname ++;
		else
			realname = argv[i];

		if (strlen(realname) > (sizeof name - 1))
		{
			fprintf(stderr, "cquote: file name too long\n");
			if (fclose(fo))
			{
				fprintf(stderr, "cquote: could not close output file '%s'\n", argv[1]);
				return 1;
			}
			return 1;
		}

		strcpy(name, realname);
		clean(name);

		fi = fopen(argv[i], "rb");

		fprintf(fo, "\n/* %s */\n\n", name);

		fputc('\"', fo);
		c = fgetc(fi);
		while (c != EOF)
		{
			int eol = 0;

			switch (c)
			{
				case '\"':
					fprintf(fo, "\\\"");
					break;

				case '\\':
					fprintf(fo, "\\\\");
					break;

				case '\r':
				case '\n':
					eol = 1;
					break;

				default:
					fputc(c, fo);
					break;
			}

			if (eol)
			{
				fprintf(fo, "\\n\"\n\"");
				while ((c = fgetc(fi)) == '\r' || c == '\n')
					;
			}
			else
			{
				c = fgetc(fi);
			}
		}

		fprintf(fo, "\\n\"\n");

		if (fclose(fo))
		{
			fprintf(stderr, "cmapdump: could not close output file '%s'\n", argv[1]);
			return 1;
		}

	}

	if (fclose(fo))
	{
		fprintf(stderr, "cmapdump: could not close output file '%s'\n", argv[1]);
		return 1;
	}

	return 0;
}