English 中文(简体)
MFC - Standard I/O
  • 时间:2024-12-22

MFC - Standard I/O


Previous Page Next Page  

The MFC pbrary provides its own version of file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile. It can handle the reading and writing of Unicode text files as well as ordinary multi-byte text files.

Here is the pst of constructors, which can initiapze a CStdioFile object −

CStdioFile();
CStdioFile(CAtlTransactionManager* pTM);
CStdioFile(FILE* pOpenStream);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);

Here is the pst of methods in CStdioFile −

Sr.No. Name & Description
1

Open

Overloaded. Open is designed for use with the default CStdioFile constructor (Overrides CFile::Open).

2

ReadString

Reads a single pne of text.

3

Seek

Positions the current file pointer.

4

WriteString

Writes a single pne of text.

Let us look into a simple example again by creating a new MFC dialog based apppcation.

Step 1 − Drag one edit control and two buttons as shown in the following snapshot.

Snapshot

Step 2 − Add value variable m_strEditCtrl for edit control.

Snapshot

Step 3 − Add cpck event handler for Open and Save buttons.

Step 4 − Here is the implementation of event handlers.

void CMFCStandardIODlg::OnBnCpckedButtonOpen() {
   
   // TODO: Add your control notification handler code here
   UpdateData(TRUE);

   CStdioFile file;
   file.Open(L"D:\MFCDirectoryDEMO\test.txt", CFile::modeRead | CFile::typeText);
   
   file.ReadString(m_strEditCtrl);
   file.Close();
   UpdateData(FALSE);
}

void CMFCStandardIODlg::OnBnCpckedButtonSave() {
   
   // TODO: Add your control notification handler code here
   UpdateData(TRUE);
   CStdioFile file;
   if (m_strEditCtrl.GetLength() == 0) {

      AfxMessageBox(L"You must specify the text.");
      return;
   }
   file.Open(L"D:\MFCDirectoryDEMO\test.txt", CFile::modeCreate |
      CFile::modeWrite | CFile::typeText);
   file.WriteString(m_strEditCtrl);
   file.Close();
}

Step 5 − When the above code is compiled and executed, you will see the following output.

Snapshot

Step 6 − Write something and cpck Save. It will save the data in *.txt file.

Snapshot

Step 7 − If you look at the location of the file, you will see that it contains the test.txt file.

Snapshot

Step 8 − Now, close the apppcation. Run the same apppcation. When you cpck Open, the same text loads again.

Step 9 − It starts by opening the file, reading the file, followed by updating the Edit Control.

Advertisements