strcut.c 2.2 KB

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