读写txt文件 中文乱码
读取txt文件中的内容放如cstring变量中
读取txt文件中一行数据
CString filePath; CStdioFile file; //打开文件 if(!file.Open(filePath,CFile::modeRead)) { ::AfxMessageBox(_T("文件打开失败!")); return; } //读取文件内容 CString strText = _T(" "); file.ReadString(strText)); //关闭文件 file.Close();
读取txt文件中内容
CStdioFile file; if (PathFileExists(m_iniPath)) { file.Open(m_iniPath, CFile::modeRead); CString sS = _T(""); while (file.ReadString(sS)) { //中文乱码 ReadStringCharToUnicode(sS); } file.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;
}
//参考:https://www.cnblogs.com/go2anywhere/p/4708414.html

浙公网安备 33010602011771号