module_05.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <iconv.h>
  6. #define BOLD_GRAY "\033[1;90m"
  7. #define RED "\033[0;31m"
  8. #define WHITE "\033[0;37m"
  9. #define RESET "\033[0m"
  10. // Размер буфера для чтения
  11. #define BUFFER_SIZE 4096
  12. int module_05_run(const char *filename) {
  13. char log_msg[1024];
  14. FILE *file = fopen(filename, "rb");
  15. if (!file) {
  16. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "File type not recognized: %s" RESET, strerror(errno));
  17. printf("%s\n", log_msg);
  18. return 1;
  19. }
  20. unsigned char *buffer = malloc(BUFFER_SIZE);
  21. if (!buffer) {
  22. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Memory allocation failed" RESET);
  23. printf("%s\n", log_msg);
  24. fclose(file);
  25. return 1;
  26. }
  27. size_t read_bytes = fread(buffer, 1, BUFFER_SIZE, file);
  28. fclose(file);
  29. if (read_bytes == 0) {
  30. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "File type not recognized: Empty file" RESET);
  31. printf("%s\n", log_msg);
  32. free(buffer);
  33. return 1;
  34. }
  35. iconv_t cd = iconv_open("UTF-8", "UTF-8");
  36. if (cd == (iconv_t)-1) {
  37. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Error initializing iconv" RESET);
  38. printf("%s\n", log_msg);
  39. free(buffer);
  40. return 1;
  41. }
  42. char *inbuf = (char *)buffer;
  43. size_t inbytesleft = read_bytes;
  44. char *outbuf = malloc(BUFFER_SIZE);
  45. if (!outbuf) {
  46. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " RED "Memory allocation failed" RESET);
  47. printf("%s\n", log_msg);
  48. iconv_close(cd);
  49. free(buffer);
  50. return 1;
  51. }
  52. char *outptr = outbuf;
  53. size_t outbytesleft = BUFFER_SIZE;
  54. size_t result = iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft);
  55. if (result == (size_t)-1) {
  56. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " WHITE "Not UTF-8, possible binary or other encoding" RESET);
  57. } else {
  58. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library iconv: " WHITE "Compatible with UTF-8" RESET);
  59. }
  60. printf("%s\n", log_msg);
  61. iconv_close(cd);
  62. free(outbuf);
  63. free(buffer);
  64. return 0;
  65. }