conv_encoding.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include "mbfl/mbfilter.h"
  11. static void hexdump(const mbfl_string *ptr)
  12. {
  13. unsigned int i;
  14. for (i = 0; i < ptr->len; i++) {
  15. printf("%%%02x", ptr->val[i]);
  16. }
  17. printf(" (%u)\n", ptr->len);
  18. }
  19. int main(int argc, char **argv)
  20. {
  21. enum mbfl_no_encoding from_encoding, to_encoding;
  22. enum mbfl_no_language no_language;
  23. mbfl_buffer_converter *convd = NULL;
  24. mbfl_memory_device dev;
  25. mbfl_string string, result, *ret;
  26. int final = 0;
  27. int state = 0;
  28. if (argc < 4) {
  29. fprintf(stderr, "Usage: %s lang to_encoding from_encoding\n", argv[0]);
  30. return EXIT_FAILURE;
  31. }
  32. if ((no_language = mbfl_name2no_language(argv[1])) ==
  33. mbfl_no_language_invalid) {
  34. printf("Unsupported NLS: %s\n", argv[1]);
  35. return EXIT_FAILURE;
  36. }
  37. if ((to_encoding = mbfl_name2no_encoding(argv[2])) ==
  38. mbfl_no_encoding_invalid) {
  39. printf("Unsupported encoding: %s\n", argv[2]);
  40. return EXIT_FAILURE;
  41. }
  42. if ((from_encoding = mbfl_name2no_encoding(argv[3])) ==
  43. mbfl_no_encoding_invalid) {
  44. printf("Unsupported encoding: %s\n", argv[3]);
  45. return EXIT_FAILURE;
  46. }
  47. convd = mbfl_buffer_converter_new(from_encoding, to_encoding, 0);
  48. do {
  49. mbfl_memory_device_init(&dev, 0, 4096);
  50. mbfl_string_init_set(&string, no_language, from_encoding);
  51. for (;;) {
  52. const int c = fgetc(stdin);
  53. if (c == EOF) {
  54. final = 1;
  55. break;
  56. } else if (c == 10) {
  57. if (state == 1) {
  58. state = 0;
  59. continue;
  60. }
  61. break;
  62. } else if (c == 13) {
  63. state = 1;
  64. break;
  65. }
  66. if (dev.pos >= dev.length) {
  67. if (dev.length + dev.allocsz < dev.length) {
  68. printf("Unable to allocate memory\n");
  69. return EXIT_FAILURE;
  70. }
  71. mbfl_memory_device_realloc(&dev, dev.length + dev.allocsz,
  72. dev.allocsz);
  73. }
  74. dev.buffer[dev.pos++] = (unsigned char)c;
  75. }
  76. mbfl_memory_device_result(&dev, &string);
  77. mbfl_string_init_set(&result, no_language, to_encoding);
  78. ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
  79. hexdump(&result);
  80. mbfl_string_clear(&result);
  81. mbfl_string_clear(&string);
  82. } while (!final);
  83. mbfl_buffer_converter_delete(convd);
  84. return EXIT_SUCCESS;
  85. }