本文展示一個基於 MFC 文檔/視圖架構的日記程式儲存邏輯,涵蓋 CFileDialog 檔案選擇、CFile/CArchive 序列化存檔、以及狀態旗標管理。
2024-05-20.txt)*.txt,啟用覆蓋提示CFile::modeCreate | modeReadWrite | shareExclusive 獨佔建立檔案CArchive::store 將編輯控制項內容 (m_sComment) 序列化寫入bSave 與當前檔名 m_sFileNamevoid CDiaryDlg::OnButtonSave() {
// 1. 取得日期構建預設檔名
int iYear = m_cMonthView.GetYear();
int iMonth = m_cMonthView.GetMonth();
int iDay = m_cMonthView.GetDay();
CString sFileName;
sFileName.Format(_T("%d-%d-%d.txt"), iYear, iMonth, iDay);
// 2. 設定檔案對話框
CFileDialog dlg(FALSE, _T("txt"), sFileName,
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("文本文件(*.txt)|*.txt||"), this);
dlg.m_ofn.lpstrTitle = _T("保存日記文件");
// 3. 執行對話框並處理結果
if (dlg.DoModal() == IDOK) {
CString fileName = dlg.GetPathName();
// 獨佔建立/開啟檔案
CFile file(fileName,
CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive);
// 序列化存檔
CArchive ar(&file, CArchive::store | CArchive::bNoFlushOnDelete);
UpdateData(TRUE); // 從控制項讀取資料到變數
ar << m_sComment; // 寫入字串
ar.Close();
// 4. 更新狀態
bSave = TRUE;
m_sFileName = fileName;
}
}
bSave 已真則直接覆寫原檔的邏輯,實作時可啟用以支援「儲存」與「另存新檔」區分try-catch(CFileException*) 捕捉磁碟滿、權限不足等異常CStdioFile 配合 CFile::typeUnicodeSetTimer 定期觸發無提示存檔此範例展示了 MFC 序列化機制在簡單文本儲存場景的標準用法,代碼結構清晰,易於整合至 SDI/MDI 文檔類的 Serialize() 虛函數中,實現統一的存讀介面。