Reading a file name using CFileDialog

There is a predefined dialog class that is used to read the name of a file from the file system. Most Windows applications use this standard dialog when opening a file and saving a file. The name of this class is CFileDialog.

CFileDialog dlg(TRUE);
if (dlg.DoModal() == IDOK) {
TRACE(dlg.GetFileName());
}

Importing from a file

Importing data from a file is very similar to the technique used in Java when reading from a BufferedReader. The class to use in C++ is CStdioFile.

In this example, only the first line of the file is read. That line copied to the message string that is stored in the document. The method SaveModify handles the task of prompting the user to save the file if the document has changed. If the user wants to save the file, then SaveModify will also call Serialize.

void CFileDemoDoc::OnFileImportfile()
{
	CFileDialog dlg(TRUE);
	if (dlg.DoModal() == IDOK) {
		CStdioFile file;
		if (!file.Open(dlg.GetFileName(), CFile::modeRead | CFile::typeText)) {
			TRACE(("Unable to open file %s\n", dlg.GetFileName());
			return;
		}
		if (!SaveModified()) {
			return;
		}
		CString line;
		if (file.ReadString(line)) {
			TRACE("%s\n", line);
			m_message = line;
			UpdateAllViews(NULL);
			SetModifiedFlag();
		}
		file.Close();
	}
}

Saving data in the Registry

It is also possbile to save data in the Registry. In the InitInstance method of the App, be sure to call
SetRegistryKey(_T("Any string that you want"));
This will force the use of the Registry. If this call is omitted, then a .INI file will be created for the application.

To write a value in the registry, make up a name for a subsection, and a name for the value.
AfxGetApp()->WriteProfileString(subsection, name, value);
To read from the registry, use the subsection name, and the name for the value.
AfxGetApp()->GetProfileString(subsection, name)

A logical place to update the registry is when the view is destroyed. Initialization can be done in OnInitialUpdate.
Note: Care must be taken to ensure that the value is only read the first time that the view is opened. Declare a member variable in the view and initialize it to true, then set it to false after the registry has been read. Otherwise, the registry will be read every time File New is selected.

void CFileDemoView::OnInitialUpdate()
{
	CView::OnInitialUpdate();

	// TODO: Add your specialized code here and/or call the base class
	if (m_bReadRegistry) {
		GetDocument()->m_message = AfxGetApp()->GetProfileString("File Demo", "Message");
		m_bReadRegistry = false;
	}
}

void CFileDemoView::OnDestroy()
{
	CView::OnDestroy();

	// TODO: Add your message handler code here
	AfxGetApp()->WriteProfileString("File Demo", "Message", GetDocument()->m_message);
}