VS2012
微软MFC帮助文档地址https://docs.microsoft.com/zh-cn/cpp/mfc/reference/cfile-class?view=msvc-160#getlength
1.控制台项目
#include <iostream> #include <afx.h> using namespace std; int main() { //CFile file("D:\File.txt",CFile::modeReadWrite); CFile file;//文件类 CFileException e;//文件异常类 //模式又读又写的去打开文件 if (file.Open("D:\File.txt", CFile::modeReadWrite, &e)) { cout << "成功" << endl; BYTE buffer[0x1000]; DWORD dwBytesRemaining = file.GetLength(); while (dwBytesRemaining) { memset(buffer, 0, 0x1000); UINT nBytesRead = file.Read(buffer, sizeof(buffer)); dwBytesRemaining -= nBytesRead; cout << buffer << endl; } file.Close(); } else { if (e.m_cause == CFileException::fileNotFound) { cout << "失败:文件没找到" << endl; } //e.Delete(); } cout << "Hello" << endl; getchar(); return 0; }
2.MFC项目
void CDemo2Dlg::OnBnClickedButton1() { // TODO: 在此添加控件通知处理程序代码 try { m_edit_text.Empty(); CFile file("D:\File.txt", CFile::modeReadWrite); BYTE buffer[0x1000]; DWORD dwBytesRemaining = file.GetLength(); while (dwBytesRemaining) { memset(buffer, 0, 0x1000); UINT nBytesRead = file.Read(buffer, sizeof(buffer)); dwBytesRemaining -= nBytesRead; m_edit_text.Append(CString(buffer)); } file.Close(); UpdateData(FALSE); } catch(CFileException* e) { e->ReportError(); e->Delete(); } }
Caesar卢尚宇
2021年1月12日