首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

MFC CFile 類文件讀寫與指針定位完整指南

     編輯:關於VC++

一、打開文件

CFile file(_T("text.txt"),
    CFile::modeReadWrite | CFile::modeNoTruncate | CFile::modeCreate);

常用模式標志:

  • modeRead / modeWrite / modeReadWrite
  • modeCreate:文件不存在則創建
  • 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 操作後文件指針自動後移;二進制模式下無文本轉換。

三、文件指針定位

1. Seek 通用定位

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 字節處

2. 便捷定位函數

file.SeekToBegin();      // 等同 Seek(0, begin)
file.SeekToEnd();        // 等同 Seek(0, end)
ULONGLONG pos = file.GetPosition(); // 獲取當前指針位置
ULONGLONG len = file.GetLength();   // 獲取文件長度

3. 獲取文件狀態

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(); }
  • 大文件(>4GB)需使用 64 位版本 CFile::GetLength、Seek 返回 ULONGLONG。
  • 多線程環境下對同一文件操作需自行加鎖同步。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved