C++文件操作——文本写入

来源:互联网 发布:算法导论第四章思考题 编辑:程序博客网 时间:2024/05/23 00:07

文本写入,一般有以下几种方式

(1).采用C语言的fputs函数

USES_CONVERSION;  char * pLogPath = T2A(FileDlg.GetPathName());  FILE *fp = fopen(pLogPath, "w");  if(NULL == fp)  {  AfxMessageBox(L"failed to open txt\n");  return;}  CString strBuffer;m_CtrlEditRead.GetWindowText(strBuffer);//调用函数,T2A和W2A均支持ATL和MFC中的字符转换  char * chBuf = T2A(strBuffer); fputs(chBuf,fp);fclose(fp); 
如果需要持续追加写入的话,可以采用fseek对指针进行操作

FILE*pFile=NULL;do {fopen_s(&pFile,pLogPath,"at+");} while (pFile==NULL);fseek(pFile,0L,2);//追加到文件末尾fputs(chBuf,pFile);fclose(pFile);
(2).采用C++的ofstream输出流

ofstream outFile(FileDlg.GetPathName());if (outFile.is_open()){CString strBuffer;m_CtrlEditRead.GetWindowText(strBuffer);USES_CONVERSION;  //调用函数,T2A和W2A均支持ATL和MFC中的字符转换  char * chBuf = T2A(strBuffer); //outFile<<chBuf;outFile.write(chBuf,strlen(chBuf));}outFile.close();
(3).采用MFC中的CStdioFile类相关函数

char * pOldLocale = _strdup(setlocale(LC_CTYPE, NULL));setlocale(LC_CTYPE, "chs");CStdioFile File(FileDlg.GetPathName(),CFile::modeCreate|CFile::modeReadWrite);  CString strBuffer;m_CtrlEditRead.GetWindowText(strBuffer);File.WriteString(strBuffer);File.Flush();  //文件操作结束关闭  setlocale(LC_CTYPE, pOldLocale);free(pOldLocale);File.Close();