通过c++ 读写文本文件的中文乱码的解决方法
前提:VS2010 ,MFC ,文本文件为ANSI格式。
读文件:
CString str,fileContent;
CStdioFile myFile, File;
if(myFile.Open(GeneralUtils::GetModuleDir()+_T(\\mx.txt), CFile::modeRead))
{
//读取
while(myFile.ReadString(str))
{
str = str + _T("\n");
ReadStringCharToUnicode(str);
fileContent = fileContent + str;
}
myFile.Close();
}
写文件:
*.h
#include <locale.h>
*.cpp
setlocale(LC_CTYPE,"chs");
myFile.Open(GeneralUtils::GetModuleDir()+_T(\\mx2.txt), CFile::modeWrite | CFile::modeCreate);
myFile.WriteString(fileContent);
myFile.Close();
void ReadStringCharToUnicode(CString &str)
{
char *szBuf = new char[str.GetLength() + 1];//注意“+1”,char字符要求结束符,而CString没有
memset(szBuf, '\0',str.GetLength());
int i;
for ( i = 0 ; i < str.GetLength(); i++)
{
szBuf[i] = (char)str.GetAt(i);
}
szBuf[i] = '\0';//结束符。否则会在末尾产生乱码。
int nLen;
WCHAR *ptch;
CString strOut;
if(szBuf == NULL)
{
return ;
}
nLen = MultiByteToWideChar(CP_ACP, 0, szBuf, -1, NULL, 0);//获得需要的宽字符字节数
ptch = new WCHAR[nLen];
memset(ptch, '\0', nLen);
MultiByteToWideChar(CP_ACP, 0, szBuf, -1, ptch, nLen);
str.Format(_T("%s"), ptch);
if(NULL != ptch)
delete [] ptch;
ptch = NULL;
if(NULL != szBuf)
delete []szBuf;
szBuf = NULL;
return ;
}
最新文章
- Node.js:OS模块
- XtraBackup出现 Can't connect to local MySQL server through socket '/tmp/mysql.sock'
- 【Java每日一题】20161020
- Meet Python: little notes
- linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 )
- Git 10 周年之际,创始人 Linus Torvalds 访谈
- [Linux]常用命令与目录全拼
- FileInputStream 与 BufferedInputStream 效率对比
- careercup-链表 2.3
- json数据渲染表单元素出现的问题
- Python 安装包报错
- 第七周博客作业 <;西北师范大学| 周安伟>;
- Arrays.asList() 的使用注意
- Numpy 数组简单操作
- IOS 缓存方案(按需缓存 、 预缓存)及 低网速模拟
- 并发队列ConcurrentLinkedQueue、阻塞队列AraayBlockingQueue、阻塞队列LinkedBlockingQueue 区别和使用场景总结
- Collabtive 系统 SQL 注入实验(补充)
- kubeadm高可用master节点部署文档
- 【剑指offer】第一个只出现一次的字符
- 9012年,我终于找到了Pypi稳定的源....