CFile

CFile class is used for opening a file. This can operate on a file handle which is already opened with Win32 CreateFile/OpenFile. However File path as string should be given to open a new file. This can be given in overloaded constructor CFile() or in Open() member call.

CFile constructor

CFile();

CFile(HANDLE hFile);

CFile(
  LPCTSTR lpszFileName,
  UINT nOpenFlags
);

CFile(
  LPCTSTR lpszFileName,
  UINT nOpenFlags,
  CAtlTransactionManager* pTM
);
Parameters hFile Handle of a file to attach to the CFile object. lpszFileName Relative or full path of a file to attach to the CFile object. nOpenFlags Bitwise combination (OR) of file access options for the specified file. See the Remarks section for possible options. pTM Pointer to CAtlTransactionManager object

File open flags

nOpenFlags Sharing and access mode. Specifies the action to take when opening the file. You can combine options listed below by using the bitwise-OR (|) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional. The values are as follows:

CFile::modeCreate Directs the constructor to create a new file. If the file exists already, it is truncated to 0 length.
CFile::modeNoTruncate Combine this value with modeCreate. If the file being created already exists, it is not truncated to 0 length. Thus the file is guaranteed to open, either as a newly created file or as an existing file. This might be useful, for example, when opening a settings file that may or may not exist already. This option applies to CStdioFile as well.
CFile::modeRead Opens the file for reading only.
CFile::modeReadWrite Opens the file for reading and writing.
CFile::modeWrite Opens the file for writing only.
CFile::modeNoInherit Prevents the file from being inherited by child processes.
CFile::shareDenyNone Opens the file without denying other processes read or write access to the file. Create fails if the file has been opened in compatibility mode by any other process.
CFile::shareDenyRead Opens the file and denies other processes read access to the file. Create fails if the file has been opened in compatibility mode or for read access by any other process.
CFile::shareDenyWrite Opens the file and denies other processes write access to the file. Create fails if the file has been opened in compatibility mode or for write access by any other process.
CFile::shareExclusive Opens the file with exclusive mode, denying other processes both read and write access to the file. Construction fails if the file has been opened in any other mode for read or write access, even by the current process.
CFile::shareCompat This flag is not available in 32 bit MFC. This flag maps to CFile::shareExclusive when used in CFile::Open.
CFile::typeText Sets text mode with special processing for carriage return–linefeed pairs (used in derived classes only).
CFile::typeBinary Sets binary mode (used in derived classes only).
CFile::osNoBuffer See FILE_FLAG_NO_BUFFERING in CreateFile in the Platform SDK.
CFile::osWriteThrough See FILE_FLAG_WRITE_THROUGH in CreateFile in the Platform SDK.
CFile::osRandomAccess See FILE_FLAG_RANDOM_ACCESS in CreateFile in the Platform SDK.
CFile::osSequentialScan See FILE_FLAG_SEQUENTIAL_SCAN in CreateFile in the Platform SDK.

CFile Open

Opens a file from the name/path given.

BOOL Open
(
  LPCTSTR lpszFileName,
  UINT nOpenFlags,
  CFileException* pError = NULL
);

BOOL Open
(
  LPCTSTR lpszFileName,
  UINT nOpenFlags,
  CAtlTransactionManager* pTM,
  CFileException* pError = NULL
);

Parameters

lpszFileName - A string that contains the path to the desired file. The path can be relative, absolute, or a network name (UNC).

pError - A pointer to an existing file-exception object that will receive the status of a failed operation.

pTM - Pointer to CAtlTransactionManager object

Return Value

Nonzero if the open was successful; otherwise 0. The pError parameter is meaningful only if 0 is returned.

CFile Read

Reads data from file associated with the CFile object and put into a buffer.

UINT Read
(
  [out] void* lpBuffer,
  [in] UINT  nCount
);

Parameters

lpBuffer - Pointer to the user-supplied buffer(non NULL) that is to receive the data read from the file.

nCount - The maximum number of bytes to be read from the file. For text-mode files, carriage return-line feed pairs are counted as single characters.

Return Value

The number of bytes transferred to the buffer. For all CFile classes, the return value may be less than nCount if the end of file was reached.

CFile Write

Writes data to the file associated with the CFile object from a buffer.

void Write
(
  [in] const void* lpBuffer, 
  [in] UINT nCount
);

Parameters

lpBuffer - A pointer to the user-supplied buffer that contains the data to be written to the file.

nCount - The number of bytes to be transferred from the buffer. For text-mode files, carriage return-line feed pairs are counted as single characters.

Return

None, Write throws an exception in response to several conditions, including the disk-full condition.

CFile METHODS

MethodDescription
AbortCloses a file ignoring all warnings and errors.
CloseCloses a file and frees the object.
DuplicateConstructs a duplicate object based on this file.
FlushFlushes any data yet to be written.
GetFileName Retrieves the filename of the selected file.
GetFilePath Retrieves the full file path of the selected file.
GetFileTitle Retrieves the title of the selected file.
GetLength Retrieves the length of the file.
GetPosition Retrieves the current file pointer.
GetStatus Retrieves the status of the open file, or in the static version, retrieves the status of the specified file (static, virtual function).
LockRange Locks a range of bytes in a file.
Open Safely opens a file with an error-testing option.
Read Reads (unbuffered) data from a file at the current file position.
Remove Deletes the specified file (static function).
Rename Renames the specified file (static function).
Seek Positions the current file pointer.
SeekToBegin Positions the current file pointer at the beginning of the file.
SeekToEnd Positions the current file pointer at the end of the file.
SetFilePath Sets the full file path of the selected file.
SetLength Changes the length of the file.
SetStatus Sets the status of the specified file (static, virtual function).
UnlockRange Unlocks a range of bytes in a file.
Write Writes (unbuffered) data in a file to the current file position.

CFile::Open() example

This promram is a clone of DOS COPY command. It takes two arguments source file and destination file. Source file is opened with read flag and destication file is opened with write flag. It show how these open flags will be used. It copies the content of source file to destination file.

/* mycopy.cpp This console program uses CFile to copy binary files. */
/* syntax: mycopy */

#include <afx.h>
#include <afxwin.h>
#include <iostream>

using namespace std;

CWinApp theApp;

int main(int argc, char *argv[])
{
  if (!AfxWinInit(GetModuleHandle(NULL), NULL, GetCommandLine(), 0))
  {
    cout << "panic: MFC couldn't initialize!" << endl;
    return 1;
  }

  CFile sourceFile;
  CFile destFile;

  if (argc != 3)
  {
    cout << "usage: " << argv[0];
    cout << " " << endl;
    cout << endl;
    return 1;
  }

  CFileException ex;

  /* Open source file in read, shared write deny node */
  /* file should not be in write mode by another program */
  /* while this is open in my app. i.e. shareDenyWrite */
   
  if (!sourceFile.Open(argv[1],
      CFile::modeRead | CFile::shareDenyWrite, &ex))
  {
    cout << "Couldn't open source file: ";
    return 1;
  }
  else
  {
    /* Destination file is in write mode. It will erase */
    /* existing content and write new content from the begining */
    /* modeCreate is given in case file is not present, it will be created. */

    if (!destFile.Open(argv[2], CFile::modeWrite |
        CFile::shareExclusive | CFile::modeCreate, &ex))
    {
      cout << "Couldn't open destination file: ";
      sourceFile.Close();
      return 1;
    }

    BYTE buffer[4096];
    DWORD dwRead;

    /* Content copy loop */
    do
    {
      dwRead = sourceFile.Read(buffer, 4096);
      destFile.Write(buffer, dwRead);
    }
    while (dwRead > 0);

    destFile.Close();
    sourceFile.Close();
  }
  return 0;
}

About our authors: Team EQA

Further readings

Where is WinMain() function in MFC application ?

MFC hides WinMain in its framework and includes source file on WinMain(). This explains how framework calls global CWinApp::Initinstance() from entry WinMain.

What is the utility of CWinApp class?

This is constructed during global C++ objects are constructed and is already available when Windows calls the WinMain function, which is supplied by the ...

Basic steps in Win32 GUI Application with source code.

Define a custom Window class structure, Register the class name, CreateWindow, Show windows and write message get and dispatch loop statements. Define the Window CallBack procedure and write the handlers.

What is a Window CallBack procedure and what is its utility?

DispatchMessage() is a API which indirectly triggers the Window CallBack procedure. Message structure members from this function are passed to the CallBack procedure. CallBack procedure should implement event handlers depending on the need of the application.

What are LPARAM and WPARAM in window proc function?

LPARAM and WPARAM are the two parameters in Window CallBack procedure. They signifies parameters of various events. They are used in handing individual events.

What are the basic steps of a typical MFC based application?

We need to write WinMain and need to follow all these in a Win32 application. However we need not to write much if we are writing an application with MFC ...

#