MFC - 標準I/O



MFC 庫提供了自己的檔案處理版本。這是透過名為 CStdioFile 的類完成的。CStdioFile 類派生自 CFile。它可以處理 Unicode 文字檔案和普通多位元組文字檔案的讀取和寫入。

以下是可以初始化 CStdioFile 物件的建構函式列表:

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

以下是 CStdioFile 中的方法列表:

序號 名稱與描述
1

Open

過載。Open 設計用於預設的 CStdioFile 建構函式(重寫 CFile::Open)。

2

ReadString

讀取一行文字。

3

Seek

定位當前檔案指標。

4

WriteString

寫入一行文字。

讓我們再次透過建立一個新的基於 MFC 對話方塊的應用程式來檢視一個簡單的示例。

步驟 1 - 拖動一個編輯控制元件和兩個按鈕,如下圖所示。

Snapshot

步驟 2 - 為編輯控制元件新增值變數 m_strEditCtrl

Snapshot

步驟 3 - 為“開啟”和“儲存”按鈕新增單擊事件處理程式。

步驟 4 - 以下是事件處理程式的實現。

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();
}

步驟 5 - 當編譯並執行上述程式碼時,您將看到以下輸出。

Snapshot

步驟 6 - 寫入一些內容並單擊“儲存”。它將資料儲存到 *.txt 檔案中。

Snapshot

步驟 7 - 如果您檢視檔案的儲存位置,您將看到它包含 test.txt 檔案。

Snapshot

步驟 8 - 現在,關閉應用程式。執行相同的應用程式。當您單擊“開啟”時,相同的文字將再次載入。

步驟 9 - 它首先開啟檔案,讀取檔案,然後更新編輯控制元件。

廣告