File I/O, Complete Control the Old-Fashioned Way

Environment: VC++ 6

Reading and Writing Files Directly

MFC's and App Wizard's built-in serialization capabilities are great if what you are doing is within defined parameters such as stream I/O. But what about an old-fashioned, powerful way of handling files like non-Windows programmers: creating, reading, and writing files directly? There is some nifty code on Code Guru that addresses this issue via custom functions; however, there is a simple, old-fashioned way of handling file I/O at a lower level, and it's VERY powerful!

The MFC Library has the CFile class. Here are the Member Functions of the CFile Class:

Member Function Description
CFile Creates the CFile object. If passed a filename, it opens the file.
Destructor Cleans up a CFile object that's going out of scope. If the file is open, it closes that file.
Abort() Immediately closes the file with no regard for errors.
Close() Closes the file.
Duplicate() Creates a duplicate file object.
Flush() Flushes data from the stream.
GetFileName() Gets the file's filename.
GetFilePath() Gets the file's full path.
GetFileTitle() Gets the file's title (the filename without the extension).
GetLength() Gets the file's length.
GetPosition() Gets the current position within the file.
GetStatus() Gets the file's status.
LockRange() Locks a portion of the file.
Open() Opens the file.
Read() Reads data from the file.
Remove() Deletes a file.
Rename() Renames the file.
Seek() Sets the position within the file.
SeekToBegin() Sets the position to the beginning of the file.
SeekToEnd() Sets the position to the end of the file.
SetFilePath() Sets the file's path.
SetLength() Sets the file's length.
SetStatus() Sets the file's status.
UnlockRange() Unlocks a portion of the file.
Write() Writes data to the file.

As you can see, the CFile class offers real file-handling power. Here is some practical sample code to demonstrate the use of the CFile class. This creates and opens a file, and writes a string to it:

    // Create the file to Write to.
    CFile file("TESTFILE.TXT", CFile::modeCreate | 
                               CFile::modeWrite);
    // Write data to the file.
    CString message("Hello World!");
    int length = message.GetLength();
    file.Write((LPCTSTR)message, length);

Reading from a file isn't much different than writing to one:

    // Open the file to Read from.
    CFile file("TESTFILE.TXT", CFile::modeRead);
    // Read data from the file.
    char s[81];
    int bytesRead = file.Read(s, 80);
    s[bytesRead] = 0;
    CString message = s;

These examples use hard-coded filenames. For a more pleasurable user experience, and to add a nice touch to your programs, use the MFC class CFileDialog (in the online help).