微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UTF-8转换为宽字符

#ifndef UNICODE #define UNICODE #endif #include <Windows.h> #include <cstdio> #include <fstream> using namespace std; int main() { FILE* resFile; char multiByteStr[256]; ifstream oFile; FILE* exampleFile; TCHAR buffer[256]; system("chcp 65001"); resFile = _wfopen(L"foo",L"w,ccs=UTF-8"); fwprintf(resFile,L"%s",L"C:\exsistingFolder\zażółć gęśłą jaźń ☺☻♥♦• ć.txt"); fclose(resFile); oFile.open(L"foo"); oFile.getline(multiByteStr,256,'n'); oFile.close(); MultiBytetoWideChar(CP_UTF8,multiByteStr,buffer,256); wprintf(L"%s",buffer); exampleFile = _wfopen(buffer,ccs=UTF-16LE"); fwprintf(exampleFile,buffer); fclose(exampleFile); system("pause"); return 0; }

正如你所看到的,程序应该创build包含要创build文件的完整path的文件“foo” resFile ,这个新文件exampleFile应该包含一个自己的path。 尽pipe在Visual Studio 2010自动debugging过程中产生的缓冲区有正确的string,exampleFile不会被创build。 为什么?

还有一件事:为什么wprintf不输出扩展字符,尽pipe我已经把控制台的字体切换到Lucida控制台 – 可以处理uncode字符的字体。

PS。 exampleFile指向NULL ,甚至在_wfopen之后,缓冲区的最后一个字符是'/0' 。

如何开发Windows 2008 64位的C#控制台应用程序?

双重下划线的含义在一开始

Windows Lua可执行文件

是libodbc ++hibernate吗? 有没有明确的inheritance人?

在C程序中调用认的Windows可执行文件

你没有做任何错误处理。 最重要的是,当调用MultiBytetoWideChar() ,你要告诉它转换整个multiByteStr缓冲区,但是大部分缓冲区都包含垃圾,因为事先没有将其归零。 您必须使用缓冲区中的实际字符数,而不是缓冲区的最大大小。 MultiBytetoWideChar()很可能会返回一个你忽略的错误代码中还有其他几个失败点。 您需要经常检查错误,特别是在与操作系统交互时。

尝试这个:

#define UNICODE #include <Windows.h> #include <cstdio> #include <fstream> using namespace std; void pause() { wcin.ignore(); wcin.get(); } int main() { FILE* resFile; char multiByteStr[256] = {0}; ifstream oFile; FILE* exampleFile; WCHAR buffer[256] = {0}; SetConsoleOutputCP(CP_UTF8); resFile = _wfopen(L"foo",ccs=UTF-8"); if (!resFile) { wprintf(L"Unable to create foo"); goto done; } fwprintf(resFile,L"C:\exsistingFolder\zażółć gęśłą jaźń ☺☻♥♦• ć.txt"); fclose(resFile); if (!oFile.open(L"foo")) { wprintf(L"Unable to open foo"); goto done; } oFile.getline(multiByteStr,255,'n'); oFile.close(); if (MultiBytetoWideChar(CP_UTF8,-1,256) == 0) { wprintf(L"Unable to convert UTF-8 to UTF-16. Error: %u",GetLastError()); goto done; } exampleFile = _wfopen(buffer,ccs=UTF-16LE"); if (!exampleFile) { wprintf(L"Unable to create file: %s",buffer); goto done; } fwprintf(exampleFile,buffer); fclose(exampleFile); wprintf(L"created file: %s",buffer); done: pause(); return 0; }

为什么要混合和匹配你的I / O库? 这是一个纯粹的(Windows)C解决方案,减去错误检查:

#include <stdio.h> #include <stdlib.h> int main() { FILE* pFile; wchar_t buffer[256]; _wfopen_s(&pFile,L"foo",ccs=UTF-8"); fputws(L"C:/existingFolder/zażółć gęśłą jaźń ☺☻♥♦• ć.txt",pFile); fclose(pFile); _wfopen_s(&pFile,L"r,ccs=UTF-8"); fgetws(buffer,_countof(buffer),ccs=UTF-16LE"); fputws(buffer,pFile); fclose(pFile); return 0; }

解决方案非常简单 – _wfopen创建一个使用BOM编码为UTF-8的文件,而MultiBytetoWideChar函数不会删除BOM,所以我们需要手动解决这个问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐