一、CFile簡介
CFile是MFC Library中常用的文件讀寫類。它可以打開、關閉、創建、寫入和讀取文件。CFile可以讀寫二進制文件和文本文件。使用CFile需要包含頭文件“afx.h”和“file.h”,其中“file.h”定義了CFile類。
二、打開、關閉、創建文件
在使用CFile讀寫文件時,首先需要打開文件。打開文件包括讀取和寫入兩個操作。在打開文件前需要知道文件的路徑、名稱和操作類型。文件路徑可以包含相對路徑和絕對路徑。CFile支持的操作類型有:CFile::modeRead只讀模式;CFile::modeWrite寫模式,不保留原文件內容;CFile::modeReadWrite讀寫模式,不保留原文件內容;CFile::modeCreate創建文件;CFile::modeNoTruncate文件已存在則不清空原有數據,只在原有數據後追加數據;CFile::modeNoInherit文件不能被繼承。
// 打開一個文件,讀寫模式,文件已存在,如果沒有文件則創建 CFile file(L"C:\\example.txt", CFile::modeReadWrite | CFile::modeCreate); // 關閉文件 file.Close();
三、讀取文件內容
在打開文件讀取操作後,可以使用Read()或ReadHuge()函數來讀取文件的內容。Read()函數可以一次讀取指定長度的數據,ReadHuge()函數適用於讀取大文件。
Read()函數:
// 打開文件,讀模式 CFile file(L"C:\\example.txt", CFile::modeRead); // 讀取文件中的內容 BYTE buffer[1024]; int nLength = file.Read(buffer, 1024); // 關閉文件 file.Close();
ReadHuge()函數:
// 打開文件,讀模式 CFile file(L"C:\\example.txt", CFile::modeRead | CFile::typeBinary); // 讀取文件中的內容,文件大小為2GB BYTE* buffer = new BYTE[2147483648]; int nLength = file.ReadHuge(buffer, 2147483648); // 關閉文件 file.Close(); delete[] buffer;
四、寫入文件內容
在打開文件寫入操作後,可以使用Write()或WriteHuge()函數來寫入文件的內容。Write()函數可以一次寫入指定長度的數據,WriteHuge()函數適用於寫入大文件。
Write()函數:
// 打開文件,寫模式 CFile file(L"C:\\example.txt", CFile::modeWrite); // 寫入文件中的內容 BYTE buffer[1024]; int nLength = file.Write(buffer, 1024); // 關閉文件 file.Close();
WriteHuge()函數:
// 打開文件,寫模式 CFile file(L"C:\\example.txt", CFile::modeWrite | CFile::typeBinary); // 寫入文件中的內容,文件大小為2GB BYTE* buffer = new BYTE[2147483648]; int nLength = file.WriteHuge(buffer, 2147483648); // 關閉文件 file.Close(); delete[] buffer;
五、其他常見操作
1. 獲取文件信息
使用CFile::GetStatus()函數可以獲取文件的創建時間、修改時間、文件大小等信息。
CFileStatus fileStatus; CFile::GetStatus(L"C:\\example.txt", fileStatus); COleDateTime fileTime = fileStatus.m_mtime; DWORD fileSize = fileStatus.m_size;
2. 文件位置指針移動
使用CFile::Seek()函數可以移動文件位置指針,Seek()函數的參數為偏移量和起始位置。文件位置指針可以用於讀寫操作。文件位置指針的起始位置有:CFile::begin文件開頭;CFile::current當前位置;CFile::end文件結尾。
// 打開文件,讀模式 CFile file(L"C:\\example.txt", CFile::modeRead); // 移動文件位置指針到文件結尾 file.Seek(0, CFile::end); // 關閉文件 file.Close();
3. 設置文件大小
使用CFile::SetLength()函數可以設置文件大小。文件大小必須小於等於2GB。
// 打開文件,寫模式 CFile file(L"C:\\example.txt", CFile::modeWrite); // 設置文件大小為10MB file.SetLength(10000000); // 關閉文件 file.Close();
六、總結
CFile是MFC Library中常用的文件讀寫類。通過本文的介紹,我們可以了解到如何打開、關閉、創建文件,如何讀取和寫入文件內容,以及如何進行其他常見操作。
原創文章,作者:FQNKQ,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/332285.html