-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhtmlutil.c
111 lines (89 loc) · 2.65 KB
/
htmlutil.c
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
/*
Utilities for creating HTML
*/
#include "vplanet.h"
/* WRITE_HTML_CONTENT -- Write a string to an output stream which will
appear in HTML content. Markup characters
are escaped as text entities. */
void write_html_content(FILE *fp, const char *s)
{
char c;
while ((c = *s++) != EOS) {
switch (c) {
case '&':
fputs("&", fp);
break;
case '<':
fputs("<", fp);
break;
case '>':
fputs(">", fp);
break;
default:
putc(c, fp);
break;
}
}
}
/* ESCAPE_HTML_CONTENT -- Replace any HTML meta-characters in a
string which will appear in HTML
content. If the string contains any
characters which require escaping, a new
string will be allocated and returned.
Otherwise, the argument string is simply
returned. If you call this repeatedly, it's
up to you to test that the string has been
replaced and free the buffer. */
char *escape_html_content(char *s)
{
char c;
const char *p = s;
char *result = s, *o;
size_t esclen = strlen(s) + 1;
while ((c = *p++) != EOS) {
switch (c) {
case '&':
esclen += 4;
break;
case '<':
esclen += 3;
break;
case '>':
esclen += 3;
break;
default:
break;
}
}
if (esclen > (strlen(s) + 1)) {
result = malloc(esclen);
if (result == NULL) {
fprintf(stderr, "escape_html_content: cannot allocate %d byte escaped string\n",
(int) esclen);
abort();
}
o = result;
while ((c = *s++) != EOS) {
switch (c) {
case '&':
strcpy(o, "&");
o += 5;
break;
case '<':
strcpy(o, "<");
o += 4;
break;
case '>':
strcpy(o, ">");
o += 4;
break;
default:
*o++ = c;
break;
}
}
*o++ = EOS;
assert(esclen == (strlen(result) + 1));
}
return result;
}