C 语言下 读包含中文的unicode文件

C语言 码拜 9年前 (2015-11-12) 1602次浏览
各位大牛,讨教一下本人想读取一个unicode编码的txt文件,里面包含中文,
为什么只能读到16进制数组,而不能转成字符串?调试时可以看到文件已经正确读取到数据
C 语言下 读包含中文的unicode文件
测试用的unicode编码的文件内容如下:

MENUE_SAVE_P_TXT                <""保存"">

程序代码如下,小弟哪里写的不对,帮本人指出来啊,愁了好几天了

#define _TRUNCATE 100  
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#define SIZE1 80
void read_unicode()
{
	int string_size;
	FILE* file = _wfopen(L"SecondFile.txt", L"rb");  
	if (file == NULL)  
	{  
		perror("open file errror");  
		system("pause");  

	}  
	wchar_t line[SIZE1];  
	wmemset(line, ""\0"", SIZE1);  
	if(fgetws(line, SIZE1, file) != NULL)
	{
		wchar_t *WStr = line;

		size_t len = wcslen(WStr) + 1;

		size_t converted = 0;

		char *CStr;

		CStr=(char*)malloc(len*sizeof(char));
		//得到的是乱码 
		wcstombs(CStr, WStr, len*sizeof(char));
	}
 
	fclose(file);
}
int main() {
  read_unicode();
    return 0;
}
解决方案:40分
首先读取的是ascii码,然后转成unicode
参考c/c++ 
http://blog.csdn.net/u010370871/article/details/48029071
代码如下

#include <iostream>
#include <sstream>
#include <fstream>
#include <windows.h>
using namespace std;
int main()
{ 
	cout<<"input the strFilename:"<<endl;
	string strFilename;
	cin>>strFilename;
	ifstream infile(strFilename.c_str());
	string strGetString;
	getline(infile,strGetString);
	int nGetStringSize=strGetString.length();
	DWORD dwStringSize=MultiByteToWideChar(CP_ACP, 0, strGetString.c_str(), nGetStringSize, NULL, 0);
	wchar_t *wchGetString=new wchar_t[dwStringSize+1];
	wmemset(wchGetString, L""\0"", dwStringSize+1);
	//进行转换
	int nRet=MultiByteToWideChar(CP_ACP, 0, strGetString.c_str(), nGetStringSize, wchGetString, dwStringSize);
	if(nRet<=0)
	{
		cout<<"转换失败"<<endl;
		DWORD dwErr=GetLastError();
		switch(dwErr)
		{
		case ERROR_INSUFFICIENT_BUFFER:
			printf("ERROR_INSUFFICIENT_BUFFER\n");
			break;
		case ERROR_INVALID_FLAGS:
			printf("ERROR_INVALID_FLAGS\n");
			break;
		case ERROR_INVALID_PARAMETER:
			printf("ERROR_INVALID_PARAMETER\n");
			break;
		case ERROR_NO_UNICODE_TRANSLATION:
			printf("ERROR_NO_UNICODE_TRANSLATION\n");
			break;
		}
	}
	wcout.imbue(locale("chs"));//中文输出
	cout<<strGetString<<endl;
	wcout<<wchGetString<<endl;
	wcout<<endl;

	return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C 语言下 读包含中文的unicode文件
喜欢 (0)
[1034331897@qq.com]
分享 (0)