MFC 写入读取记事本(中文写入)

今天上网找了一个MFC读入记事本的程序,因为我用的是单字节所以把拿来的程序改了改。

首先实现的是打开记事本的操作

CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("ALL Files(*.TXT)|*.TXT||"), AfxGetMain1Wnd());
	CString strPath = _T(" ");
	if (dlg.DoModal() == IDOK)
	{
		strPath = dlg.GetPathName();
		
		m_Edit1.SetWindowText(strPath); //将地址写在编辑控件上
		CFile file(strPath, CFile::modeRead);//只读
		int Lenth = file.GetLength();
		char *read = new char[Lenth];
		file.Read(read, Lenth);
		CString strText(read); //char *->cstring    CString xx(char*);
		str = strText;
		file.Close();
		delete[]read;
		m_open.AddString(strText);
	}

str 在头文件定义的CString;

接下来是写操作

在XXXXdlg.cpp文件中添加头文件#include<locale.h>

char* old_locale = _strdup(setlocale(LC_CTYPE, NULL));
	_tsetlocale(LC_CTYPE, _T("chs"));
	CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("ALL Files(*.TXT)|*.TXT||"), AfxGetMainWnd());
	CString strPath, strText = _T(" ");
	int len = strText.GetLength();
	char* write = new char[len];
	if (dlg.DoModal() == IDOK)
	{
		strPath = dlg.GetPathName();
		if (strPath.Right(4) != ".txt")
		strPath += ".txt";
		CStdioFile  file(strPath, CFile::modeCreate | CFile::modeWrite);
		file.WriteString(str);
		file.Close();
		setlocale(LC_CTYPE, old_locale);
		free(old_locale);//还原区域设定
	}

CStdioFile ::WriteString 可以直接读入CString类,所以这里使用。但是运行后发现写入的文件在遇到中文就停止了,在网上查了一下用

char* old_locale = _strdup(setlocale(LC_CTYPE, NULL));
  _tsetlocale(LC_CTYPE, _T("chs"));使用之后释放

setlocale(LC_CTYPE, old_locale);
 free(old_locale);//还原区域设定

在多字节模式下。我在vs2015写的 ,在VS2010这么写就会出现乱码,15就可以

猜你喜欢

转载自blog.csdn.net/weixin_40317531/article/details/84259691
MFC