How to Make Files in MFC
CFile is the base class for all MFC file classes. It is used as a tool for handling disk files. The CFile class is used to derive six file classes that represent more specialized files such as stream, memory or socket. MFC CFile objects can be opened in two ways and support read and write operations that can be controlled by means of flags. The CFile input/output services that the CFile class provides directly, are unbuffered.
Instructions
-
-
1
Create and instantiate a CFile object. This can be done in two ways, through the constructor or through the Open function. These are illustrated below.
CFile f("C:\\...\\test.txt", CFile::modeCreate|CFile::modeReadWrite);
//or
CFile f;
f.Open("C:\\...\\test.txt", CFile::modeCreate|CFile::modeReadWrite);
-
2
Understand Step 1. In both cases two parameters are accepted. The first is a string that equates to the physical file path within the hard drive. The second is one or more enumerated constants that specify how the file should be opened. "modeCreate" (0x1000) creates a new file. "modeReadWrite" (0x0002) opens a file for reading and writing. 'shareDenyNone' (0x0040) makes the file accessible to other applications for reading only. When using more than one constant, separate them with a "|". Check Microsoft's MFC database for more details on the rest of the constants.
-
-
3
Write data to a CFile object. In the code sample below a buffer of 80 int types having value zero, is written to a binary file.
int buf[80] = {0};
CFile f;
f.Open("C:\\...\\test.txt", CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
f.Write(buf, 80*sizeof(int));
-
4
Read data from a CFile object. The code sample below illustrates how the function works. Unlike Write(), the Read function returns an unsigned integer. That is the number of bytes read which can be the maximum indicated in the second parameter, or less.
int buf[80] = {0};
CFile f;
//assume file exists and has data
f.Open("C:\\...\\test.txt", CFile::ModeReadWrite|CFile::typeBinary);
UINT bytesRead = f.Read(buf, 80*sizeof(int));
-
5
Close the file. You can use the Close function explicitly or wait for the object to go out of scope in which case its destructor will call Close() automatically.
f.Close();
-
1
Tips & Warnings
If you need to read or write data row by row as in a matrix it is best you use the CStdioFile class.
Do not open a CFile object at construction without exception handling.