MFC › 7. Data, System and Interop
Files, the Registry and INI Settings
CFile, CStdioFile and persistent application settings.
intermediate #mfc#cfile#cstdiofile#cfilefind#registry#crekey#getprofilestring#settings
Explanation
Files
CFile: binary file I/O:Open(path, flags, &ex),Read,Write,Seek,SeekToBegin,GetLength,SetLength,Flush,Close. Static helpers:CFile::Remove,Rename,GetStatus. Open flags combine access (modeRead,modeWrite,modeReadWrite), creation (modeCreate,modeNoTruncate) and sharing (shareDenyWrite,shareExclusive).CStdioFile: line-oriented text files withReadString(CString&)andWriteString.CMemFile: aCFilein memory, handy for tests and for serialization without a disk.CFileFind: enumerate a directory:FindFile("dir\\*.*")then aFindNextFileloop (skipIsDots());GetFileName,GetFilePath,GetLength,IsDirectory.- Errors throw
CFileException*(a pointer: calle->Delete());e->m_causeholdsCFileException::fileNotFound,accessDenied, … You can also pass aCFileExceptionobject toOpento avoid exceptions.
Settings: registry and INI
- In a
CWinAppprogram callSetRegistryKey(_T("MyCompany"))once, thenAfxGetApp()->WriteProfileInt/WriteProfileString/GetProfileInt/GetProfileString(section, entry, default). They write toHKEY_CURRENT_USER\Software\MyCompany\AppName\Section. WithoutSetRegistryKey, an.INIfile is used instead. CRegKey(<atlbase.h>) is the general registry class:Create/Open,SetStringValue,SetDWORDValue,QueryStringValue,QueryDWORDValue,DeleteValue,RecurseDeleteKey.- Use HKCU for per-user settings; writing to
HKLMneeds administrator rights.
Example
File handling, as a console program that cleans up after itself:
#include <afxwin.h>
#include <iostream>
int _tmain() {
if (!AfxWinInit(::GetModuleHandle(nullptr), nullptr, ::GetCommandLine(), 0)) return 1;
TCHAR tmp[MAX_PATH];
GetTempPath(MAX_PATH, tmp);
CString dir = CString(tmp) + _T("mfc_demo");
CreateDirectory(dir, nullptr);
CString textPath = dir + _T("\\notes.txt");
CString binPath = dir + _T("\\data.bin");
try {
{ // text file, written line by line
CStdioFile out(textPath, CFile::modeCreate | CFile::modeWrite | CFile::typeText);
out.WriteString(_T("first line\n"));
out.WriteString(_T("second line\n"));
} // closed by the destructor
{ // read it back
CStdioFile in(textPath, CFile::modeRead | CFile::typeText);
CString line;
int n = 0;
while (in.ReadString(line)) // false at end of file
std::wcout << ++n << L": " << (LPCTSTR)line << L"\n";
}
{ // binary file
CFile f(binPath, CFile::modeCreate | CFile::modeWrite);
DWORD values[3] = { 10, 20, 30 };
f.Write(values, sizeof(values));
}
{
CFile f(binPath, CFile::modeRead);
DWORD v[3] = {};
f.Seek(sizeof(DWORD), CFile::begin); // skip the first value
UINT got = f.Read(v, sizeof(DWORD) * 2);
std::wcout << L"read " << got << L" bytes: " << v[0] << L", " << v[1]
<< L" (file length " << f.GetLength() << L")\n";
}
CFileFind finder; // list the directory
BOOL more = finder.FindFile(dir + _T("\\*.*"));
while (more) {
more = finder.FindNextFile();
if (finder.IsDots()) continue; // "." and ".."
std::wcout << (LPCTSTR)finder.GetFileName() << L" " << finder.GetLength() << L" bytes\n";
}
finder.Close();
CFile f2;
CFileException ex;
if (!f2.Open(dir + _T("\\missing.txt"), CFile::modeRead, &ex)) // no exception thrown
std::wcout << L"open failed, fileNotFound = " << (ex.m_cause == CFileException::fileNotFound) << L"\n";
CFile::Remove(textPath);
CFile::Remove(binPath);
} catch (CFileException* e) { // MFC exceptions are pointers
TCHAR msg[256];
e->GetErrorMessage(msg, 256);
std::wcout << L"file error: " << msg << L"\n";
e->Delete(); // you must delete it
}
RemoveDirectory(dir);
return 0;
}
Settings in the registry. This function changes the registry, so it is only compiled here, not run:
#include <afxwin.h>
#include <atlbase.h>
void SaveAndLoadSettings() {
CRegKey key;
if (key.Create(HKEY_CURRENT_USER, _T("Software\\MyCompany\\MyApp")) == ERROR_SUCCESS) {
key.SetStringValue(_T("LastFile"), _T("C:\\docs\\report.txt"));
key.SetDWORDValue(_T("WindowWidth"), 1024);
}
TCHAR buffer[MAX_PATH];
ULONG len = MAX_PATH;
if (key.QueryStringValue(_T("LastFile"), buffer, &len) == ERROR_SUCCESS)
AfxMessageBox(buffer);
DWORD width = 800; // default if the value is missing
key.QueryDWORDValue(_T("WindowWidth"), width);
// inside a CWinApp program (after SetRegistryKey("MyCompany")) the same data is simply:
// AfxGetApp()->WriteProfileInt(_T("Window"), _T("Width"), 1024);
// int w = AfxGetApp()->GetProfileInt(_T("Window"), _T("Width"), 800);
}
Common pitfalls
- MFC throws
CFileException*by pointer. Not callingDelete()leaks, and catching by value (catch (CFileException e)) does not compile as expected. CStdioFileconverts line ends and, in a Unicode build, text mode narrows characters to the ANSI code page: non-ASCII text is lost. For UTF-8/UTF-16 files use a different approach (read bytes withCFileand convert withMultiByteToWideChar, orstd::wofstreamwith a codecvt).- Forgetting
Close()(or relying on the destructor in atryblock you leave early) keeps the file locked. CFileFind::FindNextFilemust be called before accessing the first result; the loop above handles this. The last file is processed whenFindNextFilereturnsFALSE, so use themorevariable as shown.- Writing settings to HKLM or
Program Filesfrom a normal user fails on modern Windows. Use HKCU and%AppData%. - Hard-coding paths (
C:\\temp): useGetTempPath,SHGetKnownFolderPath, orstd::filesystem::temp_directory_path.
Legacy vs modern
std::filesystem (C++17) covers directory listing, copying, deleting and path handling more simply than CFileFind: see std::filesystem, and standard streams cover text I/O (File I/O). In new code keep the MFC classes for interop with MFC APIs and serialization.
Exercises
1. What does CFile::modeCreate | CFile::modeWrite do if the file already exists?
modeCreate truncates it to zero length. Add CFile::modeNoTruncate to keep the existing contents.