日記、記事本類程式需依日期自動產生預設檔名,彈出「另存新檔」對話框,使用 `CArchive` 將 `CString` 內容序列化寫入檔案。
void CDiaryDlg::OnButtonSave()
{
// 依月曆控制項取得日期
int y = m_cMonthView.GetYear();
int m = m_cMonthView.GetMonth();
int d = m_cMonthView.GetDay();
CString defName; defName.Format(_T("%d-%d-%d.txt"), y, m, d);
CFileDialog dlg(FALSE, _T("txt"), defName,
OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("文字檔 (*.txt)|*.txt||"), this);
dlg.m_ofn.lpstrTitle = _T("儲存日記檔案");
if (dlg.DoModal() == IDOK) {
CString path = dlg.GetPathName();
CFile file(path, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive);
CArchive ar(&file, CArchive::store | CArchive::bNoFlushOnDelete);
UpdateData(TRUE); // 將控制項資料同步到 m_sComment
ar << m_sComment; // 序列化寫入
ar.Close(); file.Close();
m_sFileName = path; // 記錄目前檔案路徑
}
}
CFileDialog(FALSE, ...):`FALSE` 表示「另存新檔」模式。OFN_OVERWRITEPROMPT:檔案存在時提示覆蓋。CArchive::store:寫入模式;`bNoFlushOnDelete` 避免解構時重複 flush。
if (m_sFileName.IsEmpty()) { OnButtonSave(); return; } // 首次儲存導向另存新檔
CFile file(m_sFileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive);
CArchive ar(&file, CArchive::store);
UpdateData(TRUE); ar << m_sComment;