json_encode_str.c - randomcrap - random crap programs of varying quality
(HTM) git clone git://git.codemadness.org/randomcrap
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
json_encode_str.c (1060B)
---
1 /* encode string to JSON string */
2
3 #include <stdio.h>
4
5 #define GETCHAR getchar_unlocked
6 #define PUTCHAR putchar_unlocked
7
8 static int
9 digit2hex(int c)
10 {
11 if (c >= 0 && c <= 9)
12 return c + '0';
13 else if (c >= 10 && c <= 15)
14 return (c - 10) + 'a';
15 return 0;
16 }
17
18 int
19 main(void)
20 {
21 int c;
22
23 PUTCHAR('"');
24 while ((c = GETCHAR()) != EOF) {
25 switch (c) {
26 case '"': PUTCHAR('\\'); putchar('"'); break;
27 case '\\': PUTCHAR('\\'); PUTCHAR('\\'); break;
28 case '\b': PUTCHAR('\\'); PUTCHAR('b'); break;
29 case '\f': PUTCHAR('\\'); PUTCHAR('f'); break;
30 case '\n': PUTCHAR('\\'); PUTCHAR('n'); break;
31 case '\r': PUTCHAR('\\'); PUTCHAR('r'); break;
32 case '\t': PUTCHAR('\\'); PUTCHAR('t'); break;
33 default: /* control character */
34 if (c < 0x20) {
35 PUTCHAR('\\');
36 PUTCHAR('u');
37 PUTCHAR('0');
38 PUTCHAR('0');
39 PUTCHAR(digit2hex((c >> 4)));
40 PUTCHAR(digit2hex(c & 0x0f));
41 } else {
42 PUTCHAR(c);
43 }
44 break;
45 }
46 }
47 PUTCHAR('"');
48
49 if (ferror(stdin) || fflush(stdout) || ferror(stdout)) {
50 perror(NULL);
51 return 1;
52 }
53
54 return 0;
55 }