1 /**
2 * this is a small sample script to use libmbfl.
3 * Rui Hirokawa <hirokawa@php.net>
4 *
5 * this file is encoded in EUC-JP.
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <errno.h>
12 #include "mbfl/mbfilter.h"
13
hexdump(const mbfl_string * ptr)14 static void hexdump(const mbfl_string *ptr)
15 {
16 unsigned int i;
17
18 for (i = 0; i < ptr->len; i++) {
19 printf("%%%02x", ptr->val[i]);
20 }
21
22 printf(" (%u)\n", ptr->len);
23 }
24
main(int argc,char ** argv)25 int main(int argc, char **argv)
26 {
27 enum mbfl_no_encoding no_encoding;
28 enum mbfl_no_language no_language;
29 mbfl_memory_device dev;
30 mbfl_string string;
31 int offset, length;
32 int final = 0;
33 int state = 0;
34
35 if (argc < 5) {
36 fprintf(stderr, "Usage: %s lang encoding offset length\n", argv[0]);
37 return EXIT_FAILURE;
38 }
39
40 if ((no_language = mbfl_name2no_language(argv[1])) ==
41 mbfl_no_language_invalid) {
42 printf("Unsupported NLS: %s\n", argv[1]);
43 return EXIT_FAILURE;
44 }
45
46 if ((no_encoding = mbfl_name2no_encoding(argv[2])) ==
47 mbfl_no_encoding_invalid) {
48 printf("Unsupported encoding: %s\n", argv[2]);
49 return EXIT_FAILURE;
50 }
51
52 errno = 0;
53 offset = strtol(argv[3], NULL, 10);
54 if (errno) {
55 printf("Invalid offset: %s\n", argv[3]);
56 return EXIT_FAILURE;
57 }
58
59 length = strtol(argv[4], NULL, 10);
60 if (errno) {
61 printf("Invalid length: %s\n", argv[4]);
62 return EXIT_FAILURE;
63 }
64
65
66 do {
67 mbfl_string result;
68
69 mbfl_memory_device_init(&dev, 0, 4096);
70 mbfl_string_init_set(&string, no_language, no_encoding);
71
72 for (;;) {
73 const int c = fgetc(stdin);
74
75 if (c == EOF) {
76 final = 1;
77 break;
78 } else if (c == 10) {
79 if (state == 1) {
80 state = 0;
81 continue;
82 }
83 break;
84 } else if (c == 13) {
85 state = 1;
86 break;
87 }
88
89 if (dev.pos >= dev.length) {
90 if (dev.length + dev.allocsz < dev.length) {
91 printf("Unable to allocate memory\n");
92 return EXIT_FAILURE;
93 }
94
95 mbfl_memory_device_realloc(&dev, dev.length + dev.allocsz,
96 dev.allocsz);
97 }
98
99 dev.buffer[dev.pos++] = (unsigned char)c;
100 }
101
102 mbfl_memory_device_result(&dev, &string);
103 if (mbfl_strcut(&string, &result, offset, length)) {
104 hexdump(&result);
105 mbfl_string_clear(&result);
106 } else {
107 printf("***ERROR***\n");
108 }
109 mbfl_string_clear(&string);
110 } while (!final);
111
112 return EXIT_SUCCESS;
113 }
114