我有一个关于 MFC CFile 写函数的问题。
我正在学习 MFC 应用程序并停留在这个另存为和写入功能上。
当我点击测试按钮时,会弹出另存为对话框提示另存为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"));
关于c++ - CFile写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16889300/