返回
顶部

修改密码

首页 > 数据库 > SQLITE > 正文
为SQLite3提供一个ANSI到UTF8的互转函数

+1

-1

收藏

+1

-1

点赞0

评论0

在使用Sqlite3时必须要用到的使用方法:char* src = "...";//待转换的ANSI或UTF8字符串  char* dst = NULL;//保存由函数内部分配的内存指针, 不需要传入内存缓冲区的转换为UTF-8:to_utf8(src, &dst);  转换为ANSI:to_gb(src, &dst);返回值:零 - 失败, 非零 - 成功.  注…

在使用Sqlite3时必须要用到的

  使用方法:

  char* src = "...";//待转换的ANSI或UTF8字符串
  char* dst = NULL;//保存由函数内部分配的内存指针, 不需要传入内存缓冲区的

  转换为UTF-8:to_utf8(src, &dst);
  转换为ANSI:to_gb(src, &dst);

  返回值:零 - 失败, 非零 - 成功.
  注意:如果操作成功, 需要手动释放函数内部分配的空间:

复制代码 代码如下:

if(dst)
{
    free(dst);
    dst = NULL;
}

代码:

复制代码 代码如下:

#include <windows.h>
#include <stdio.h>int to_utf8(char* psrc, char** ppdst)
{
    int ret,ret2;
    wchar_t* pws = NULL;
    char* putf = NULL;

    ret = MultiByteToWideChar(CP_ACP, 0, psrc, -1, NULL, 0);
    if(ret<=0){
        *ppdst = NULL;
        return 0;
    }
    pws = (wchar_t*)malloc(ret*2);
    if(!pws){
        *ppdst = NULL;
        return 0;
    }
    MultiByteToWideChar(CP_ACP, 0, psrc, -1, pws, ret);
    ret2 = WideCharToMultiByte(CP_UTF8, 0, pws, -1, NULL, 0, NULL, NULL);
    if(ret2<=0){
        free(pws);
        return 0;
    }
    putf = (char*)malloc(ret2);
    if(!putf){
        free(pws);
        return 0;
    }
    if(WideCharToMultiByte(CP_UTF8, 0, pws, ret, putf, ret2, NULL, NULL)){
        *ppdst = putf;
        free(pws);
        return 1;
    }else{
        free(pws);
        free(putf);
        *ppdst = NULL;
        return 0;
    }
}

int to_gb(char* psrc, char** ppdst)
{
    int ret, ret2;
    wchar_t* pws = NULL;
    char* pgb = NULL;
    ret = MultiByteToWideChar(CP_UTF8, 0, psrc, -1, NULL, 0);
    if(ret<=0){
        *ppdst = NULL;
        return 0;
    }
    pws = (wchar_t*)malloc(ret*2);
    if(!pws){
        *ppdst = NULL;
        return 0;
    }
    MultiByteToWideChar(CP_UTF8, 0, psrc, -1, pws, ret);
    ret2 = WideCharToMultiByte(CP_ACP, 0, pws, -1, NULL, 0, NULL, NULL);
    if(ret2<=0){
        free(pws);
        return 0;
    }
    pgb = (char*)malloc(ret2);
    if(!pgb){
        free(pws);
        *ppdst = NULL;
        return 0;
    }
    if(WideCharToMultiByte(CP_ACP, 0, pws, -1, pgb, ret2, NULL, NULL)){
        *ppdst = pgb;
        free(pws);
        return 1;
    }else{*ppdst = 0;
        free(pgb);
        free(pws);
        return 0;
    }
}

by: 女孩不哭

扫一扫在手机打开

评论
已有0条评论
0/150
提交
热门评论
相关推荐
数据库表连接的简单解释
  • 操作技巧
  • 2022-05-25 18:24
  • 22 0 0
+1
SQL 行转列,列转行
  • 操作技巧
  • 2022-05-25 18:24
  • 20 0 0
+1
一起看懂Redis两种持久化方式的原理
  • 操作技巧
  • 2022-05-25 18:24
  • 32 0 0
+1
为什么要用Redis
  • 操作技巧
  • 2022-05-25 18:24
  • 13 0 0
+1
今日要闻
换一批
热点排行