Original: Nanshan A section of the simplest CFile read and write file source
Beginners programming, often encounter file reading and writing problems, here Nanshan to the vast number of beginners to write a section of the simplest CFile read and write file Source:
Read file data
void Cfileoperdlg::onbuttonread ()
{
Todo:add your control notification handler code here
CFile file;
CString filename= "Data.txt";
Char buf[1000];//read 1K
memset (buf,0,1000);//Initialize the memory to prevent garbled characters at the end of the read character
Try
{
if (!file. Open (Filename,cfile::moderead))
{
MessageBox ("No documents!");
Return
}
File. Read (buf,sizeof (BUF));
File. Close ();
m_data=buf;//to the text box CString m_data
UpdateData (false);//Display in text box
MessageBox ("read out successfully.") ");
}
catch (CFileException *e)
{
CString str;
Str. Format ("The reason read data failed is:%d", e->m_cause);
MessageBox ("str");
File. Abort ();
E->delete ();
}
}
Write file data
void Cfileoperdlg::onbuttonwrite ()
{
Todo:add your control notification handler code here
UpdateData ()//Fetch text box characters
CFile file;
CString filename= "Data.txt";
Try
{
File. Open (filename,cfile::modecreate| Cfile::modewrite);
File. Seektobegin ();
File. Write (unsigned char *) (m_data. GetBuffer (0)), m_data. GetLength ());//cstring m_data
File. Flush ();
File. Close ();
MessageBox ("Write succeeded.") ");
}
catch (CFileException *e)
{
CString str;
Str. Format (the reason for the write failure is:%d, e->m_cause);
MessageBox ("str");
File. Abort ();
E->delete ();
}
Copy Code