[英]CFile write function
我对MFC CFile写入功能有疑问。
我正在学习MFC应用程序,并停留在此另存为和写入功能上。 当我单击TestButton时,将弹出一个“另存为”对话框,提示您另存为txt文件。
void CLearnDlg::OnBnClickedButtonTest()
{
CString m_strPathName;
char* File;
TCHAR szFilters[] =
_T ("Text files (*.txt)¦*.txt¦All files (*.*)¦*.*¦¦");
CFileDialog dlg (FALSE, _T ("txt"), _T ("*.txt"),
OFN_OVERWRITEPROMPT, szFilters);
if (dlg.DoModal () == IDOK)
m_strPathName = dlg.GetPathName();
CFile DataFile(m_strPathName, CFile::modeReadWrite | CFile::modeCreate);
char buffer0[100] = "TEST0";
char buffer1[100] = "TEST1";
int GetLength;
for (int i=0; i<2; i++)
{
File = (("%S, %S\n\n"), buffer0, buffer1);
GetLength = strlen(File);
DataFile.Write(File, GetLength);
}
DataFile.Close();
MessageBox(_T("OK"));
}
问题是如何将两个缓冲区一起写入单个File
然后将其写入DataFile
并在每次写入时换行?
保存了输出文件,但只保存了一个缓冲区(TEST1)两次,而无需转到新行。
如果您的代码正确,那么实际上您的代码有问题,那么您的编程语句
File = (("%S, %S\n\n"), buffer0, buffer1);
唯一的含义是,首先用buffer0创建File字符数组,然后用buffer1替换它,这样最后您将得到buffer1作为最终File值。
关于\\ n无法正常运行,因为它应该类似于\\ r \\ n
所以您的最终程序可能看起来像
// TODO: Add your control notification handler code here
CString m_strPathName;
char* File;
TCHAR szFilters[] =
_T ("Text files (*.txt)¦*.txt¦All files (*.*)¦*.*¦¦");
CFileDialog dlg (FALSE, _T ("txt"), _T ("*.txt"),
OFN_OVERWRITEPROMPT, szFilters);
if (dlg.DoModal () == IDOK)
m_strPathName = dlg.GetPathName();
CFile DataFile(m_strPathName, CFile::modeReadWrite | CFile::modeCreate);
char buffer0[100] = "TEST0";
char buffer1[100] = "TEST1";
int GetLength;
File = new char[strlen(buffer0)+strlen(buffer1)+2];
for (int i=0; i<2; i++)
{
strcpy(File,buffer0);
strcat(File,buffer1);
strcat(File,"\r\n");
GetLength = strlen(File);
DataFile.Write(File, GetLength);
}
DataFile.Close();
MessageBox(_T("OK"));
CDialogEx::OnOK();
}
[编辑]
// TODO: Add your control notification handler code here
CString m_strPathName;
char* File;
TCHAR szFilters[] =
_T ("Text files (*.txt)¦*.txt¦All files (*.*)¦*.*¦¦");
CFileDialog dlg (FALSE, _T ("txt"), _T ("*.txt"),
OFN_OVERWRITEPROMPT, szFilters);
if (dlg.DoModal () == IDOK)
m_strPathName = dlg.GetPathName();
CFile DataFile(m_strPathName, CFile::modeReadWrite | CFile::modeCreate);
char buffer0[100] = "TEST0";
char buffer1[100] = "TEST1";
int GetLength;
File = new char[strlen(buffer0)+strlen(buffer1)+2];
for (int i=0; i<2; i++)
{
double doublevalue;
doublevalue = 1035.25414;
sprintf(File,"%s,%s,%f\r\n", buffer0, buffer1,doublevalue); //Dumping data string and double data saparated with comma
GetLength = strlen(File);
DataFile.Write(File, GetLength);
sprintf(File,"%f>>>%s>>>%s\r\n", doublevalue,buffer1,buffer0); //Dumping data double and string data saparated with >>
GetLength = strlen(File);
DataFile.Write(File, GetLength);
}
DataFile.Close();
MessageBox(_T("OK"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.