• windows程序设计03_读取utf8文件


    这里用到的读取utf8文件的思路特别朴素.先把utf8文件按char读取到内存里.因为utf8是变长的,为了处理方便,在内存里把char转化成wchar_t,这样一个字符就是一个wchar_t.把utf8文件转成wchar_t的字符串之后,可以进行各种操作,比如统计非中文字符,对齐等.当然也包含要显示wchar_t.windows的命令行不能直接显示wchar_t字符,想显示必须再把wchar_t转成gbk或者utf8.
    看C28ShowWchar.c的代码:

    //utf-8编码
    #include <stdio.h>
    #include <windows.h>
    char* unicode2Utf8(wchar_t* unicodeStr) {
    	int cStrLen = WideCharToMultiByte(CP_UTF8, 0, unicodeStr, -1, NULL, 0, NULL, NULL);
    	char* cStr = (char*)malloc(sizeof(char) * (cStrLen + 1));
    	WideCharToMultiByte(CP_UTF8, 0, unicodeStr, -1, cStr, cStrLen + 1, NULL, NULL);
    	*(cStr + cStrLen) = '';
    	return cStr;
    }
    
    void main() {
    	wchar_t* unicodeStr = L"中国";
    	char* utf8Str = unicode2Utf8(unicodeStr);
    	printf("%s
    ", utf8Str);
    	getchar();
    }
    

    打开VS的"开发人员命令提示符",执行下面命令把命令行的编码设置成utf8:

    CHCP 65001
    

    再把字体设置成"Lucida Console"
    然后用下面命编译链接

    cl C28ShowWchar.c /source-charset:utf-8
    

    /source-charset:utf-8表示编码是utf8.再运行生成的可执行文件就能看到"中国"两个汉字.
    再看源代码C29ShowWchar1.c

    //utf-8编码
    #include <stdio.h>
    #include <windows.h>
    char* unicode2gbk(wchar_t* unicodeStr) {
    	int cStrLen = WideCharToMultiByte(CP_ACP, 0, unicodeStr, -1, NULL, 0, NULL, NULL);
    	char* cStr = (char*)malloc(sizeof(char) * (cStrLen + 1));
    	WideCharToMultiByte(CP_ACP, 0, unicodeStr, -1, cStr, cStrLen + 1, NULL, NULL);
    	*(cStr + cStrLen) = '';
    	return cStr;
    }
    
    void main() {
    	wchar_t* unicodeStr = L"中国";
    	char* gbkStr = unicode2gbk(unicodeStr);
    	printf("%s
    ", gbkStr);
    	getchar();
    }
    

    CP_ACP表示windows默认的ANSI code page,对于简体中文就是gbk.按ctrl+F5就能看到"中国"两个汉字.
    读取utf8文件的思路就是先按char把文件读到char类型的链表里.读完后把链表里的char放到一个char型的数组里.再把char型的数组转化成unicode.
    源代码如下:
    https://github.com/zhouyang209117/CppTutorial/blob/master/C/Win32Api/ch02/C22ReadUtf8File.c

    参考资料

    微软官方文档fopen_s, _wfopen_s
    WideCharToMultiByte function

  • 相关阅读:
    找零钱「Usaco2006 Dec」
    才艺表演「Usaco2018 Open」
    潜入行动「JSOI2018」
    任务安排「SDOI2012」
    BZOJ2298: [HAOI2011]problem a
    JZOJ 5818
    JZOJ 3493
    JZOJ 3470
    JZOJ 5781
    JZOJ 5778
  • 原文地址:https://www.cnblogs.com/zhouyang209117/p/7979013.html
Copyright © 2020-2023  润新知