• 在C语言中使用libiconv进行编码转换的示例


    libiconv_sample.c

    #include <stdio.h>
    #include <malloc.h>
    #include "libiconv/iconv.h"
    #ifdef _DEBUG
    #pragma comment(lib, "libiconv/libiconvd.lib")
    #else
    #pragma comment(lib, "libiconv/libiconv.lib")
    #endif
    #define BUFFER_SIZE 10 * 1024 * 1024
    int main()
    {
        const char *toCode = "GBK", *fromCode = "UTF-8";
        iconv_t conversionDescriptor = iconv_open(toCode, fromCode);
        if ((iconv_t)-1 == conversionDescriptor)
        {
            if (errno == EINVAL)
                printf("Not supported from %s to %s.
    ", fromCode, toCode);
            else
                printf("Unknown error.
    ");
        }
        else
        {
            const char *filename = "text_utf-8.txt";
            FILE *inputFile = fopen(filename, "r");
            if (inputFile)
            {
                filename = "text_gbk.txt";
                FILE *outputFile = fopen(filename, "w");
                if (outputFile)
                {
                    char *sourceBuffer = (char *)malloc(sizeof(char) * BUFFER_SIZE);
                    const char *sourcePtr = sourceBuffer;
                    size_t destinationBufferSize = BUFFER_SIZE * 2, availableSpaceOfDestinationBuffer = destinationBufferSize;
                    char *destinationBuffer = (char *)malloc(sizeof(char) * destinationBufferSize), *destinationPtr = destinationBuffer;
                    size_t numberOfCharactersRead = fread(sourceBuffer, sizeof(char), BUFFER_SIZE, inputFile);
                    iconv(conversionDescriptor, &sourcePtr, &numberOfCharactersRead, &destinationPtr, &availableSpaceOfDestinationBuffer);
                    size_t characterCount = destinationBufferSize - availableSpaceOfDestinationBuffer;
                    destinationBuffer[characterCount] = '';
                    printf(destinationBuffer);
                    fwrite(destinationBuffer, sizeof(char), characterCount, outputFile);
                    free(sourceBuffer);
                    free(destinationBuffer);
                    fclose(outputFile);
                }
                else
                    printf("Cannot open file: %s.
    ", filename);
                fclose(inputFile);
            }
            else
                printf("Cannot open file: %s.
    ", filename);
            iconv_close(conversionDescriptor);
        }
        system("pause");
        return 0;
    }

    参考链接:unnonouno/iconvpp: wrapper library of iconv for c++

  • 相关阅读:
    Guid ToString 格式
    SQL Server 自增字段归零
    一些被触动的话
    【简易教程】在网站上养一只萌咔咔的小仓鼠
    SQL分页语句
    WPF使用System.Windows.SystemParameters类获得屏幕分辨率
    WPF编程学习——窗口
    C# .net WPF无边框移动窗体
    WPF 4 Ribbon 开发 之 快捷工具栏(Quick Access Toolbar)
    转 遗传算法简介
  • 原文地址:https://www.cnblogs.com/buyishi/p/9322864.html
Copyright © 2020-2023  润新知