1 中文字符串(或中英混杂)写入文本文件
void fCStringprintf(CString str,FILE*f)
{
int len=str.GetLength();
int l=0;
for (int i=0;i<len;i++)//中文字符数统计
{
if (str[i]>255)
{
l++;
}
}
char *charstemp=new char[len+l+1];charstemp[len+l]='\0';
WideCharToMultiByte(CP_ACP,0,str,len,charstemp,len+l,NULL,NULL);
fprintf(f,"%s",charstemp);
delete []charstemp;
}
2 从文本文件中读取中文字符串(或中英混杂)
2.1 读取到CString对象中
bool fCStringscanf_s(CString *str,int len,FILE*f)
{
char *name=new char[len];
if (fscanf_s(f,"%s",name,len)!=1)
{
*str=_T("");
delete []name;
return false;
}
CString v(name);
*str=v;
delete []name;
return true;
}
2.2 读取到WCHAR数组中
bool fWCHARArrayscanf_s(WCHAR *buffer,int len,FILE*f)//参数buffer是len长度的WCHAR数组
{
char *name=new char[len];
if (fscanf_s(f,"%s",name,len)!=1)
{
delete []name;
return false;
}
ASSERT(buffer!=NULL);
for(int i=0;i<len;i++)//函数MultiByteToWideChar不会为数组的最后一个字符的下一字符赋值0,故必须先都初始化为0,表征数组的结束。
{
buffer[i]=0;
}
MultiByteToWideChar(CP_ACP,0,name,int(strlen(name)),buffer,len);
delete []name;
return true;
}
3.下面写一段代码对以上三个函数进行测试
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
//写文件
CString filename=_T("test.txt");
FILE*wf=_wfopen(filename,_T("w+"));
if (!wf)
{
return 0;
}
CString str=_T("测试代码test");//中英混杂的字符串
fCStringprintf(str,wf);
fclose(wf);
//读文件-1
FILE*f=_wfopen(filename,_T("r+"));
if (!f)
{
return 0;
}
int len=100;
WCHAR *buffer=new WCHAR[len];
fWCHARArrayscanf_s(buffer,len,f);
CString str1(buffer);
delete []buffer;
AfxMessageBox(str1);
fclose(f);
//读文件-2
f=_wfopen(filename,_T("r+"));
if (!f)
{
return 0;
}
CString str2;
fCStringscanf_s(&str2,len,f);
AfxMessageBox(str2);
fclose(f);
}
return nRetCode;
}