CFile file(_T("text.txt"),
CFile::modeReadWrite | CFile::modeNoTruncate | CFile::modeCreate);
常用模式標志:
modeRead / modeWrite / modeReadWritemodeCreate:文件不存在則創建modeNoTruncate:配合 modeCreate 使用,文件存在時不截斷(保留原內容)modeNoInherit:禁止句柄被子進程繼承shareDenyNone / shareDenyRead / shareDenyWrite / shareExclusive:共享模式char buf[100];
UINT nRead = file.Read(buf, 100); // 讀取最多 100 字節,返回實際讀取字節數
strcpy(buf, "this file is modified");
file.Write(buf, strlen(buf) + 1); // 從當前指針位置寫入
file.Close();
注意: Read/Write 操作後文件指針自動後移;二進制模式下無文本轉換。
virtual LONG Seek(LONG lOff, UINT nFrom);
參數:
nFrom:基準位置
CFile::begin:文件開頭CFile::current:當前位置CFile::end:文件結尾lOff:偏移量(可正可負)示例:
LONG offset = 1000;
LONG actual = file.Seek(offset, CFile::begin); // 指針移至距文件頭 1000 字節處
file.SeekToBegin(); // 等同 Seek(0, begin)
file.SeekToEnd(); // 等同 Seek(0, end)
ULONGLONG pos = file.GetPosition(); // 獲取當前指針位置
ULONGLONG len = file.GetLength(); // 獲取文件長度
CFileStatus status;
file.GetStatus(status);
// status.m_ctime 創建時間
// status.m_mtime 修改時間
// status.m_atime 訪問時間
// status.m_size 文件大小
// status.m_attribute 屬性(只讀/隱藏/系統/歸檔等)
// status.m_szFullName 完整路徑
CFile file;
if (!file.Open(_T("log.txt"), CFile::modeCreate | CFile::modeNoTruncate | CFile::modeWrite)) {
AfxMessageBox(_T("打開失敗"));
return;
}
file.SeekToEnd(); // 定位到文件末尾
CString log = _T("[") + CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S")) + _T("] 操作日志\r\n");
file.Write(log, log.GetLength() * sizeof(TCHAR));
file.Close();
// 回讀顯示
if (file.Open(_T("log.txt"), CFile::modeRead)) {
ULONGLONG len = file.GetLength();
CStringA content;
content.GetBufferSetLength((int)len);
file.Read(content.GetBuffer(), (UINT)len);
content.ReleaseBuffer();
AfxMessageBox(CString(content));
file.Close();
}
CFileException 捕獲文件操作錯誤:try { ... } catch (CFileException* e) { e->ReportError(); e->Delete(); }CFile::GetLength、Seek 返回 ULONGLONG。