MFC - Standard I/O


Advertisements


The MFC library 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 list of constructors, which can initialize 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 list 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 line of text.

3

Seek

Positions the current file pointer.

4

WriteString

Writes a single line of text.

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

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 click event handler for Open and Save buttons.

Step 4 − Here is the implementation of event handlers.

void CMFCStandardIODlg::OnBnClickedButtonOpen() {
   
   // 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::OnBnClickedButtonSave() {
   
   // 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 click 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 application. Run the same application. When you click Open, the same text loads again.

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



Advertisements
E-Books Store