CFile Class

 

For the latest documentation on Visual Studio 2017, see Visual Studio 2017 Documentation.

The base class for Microsoft Foundation Class file classes.

class CFile : public CObject  

Public Constructors

NameDescription
CFile::CFileConstructs a CFile object from a path or file handle.

Public Methods

NameDescription
CFile::AbortCloses a file ignoring all warnings and errors.
CFile::CloseCloses a file and deletes the object.
CFile::DuplicateConstructs a duplicate object based on this file.
CFile::FlushFlushes any data yet to be written.
CFile::GetFileNameRetrieves the filename of the selected file.
CFile::GetFilePathRetrieves the full file path of the selected file.
CFile::GetFileTitleRetrieves the title of the selected file.
CFile::GetLengthRetrieves the length of the file.
CFile::GetPositionRetrieves the current file pointer.
CFile::GetStatusRetrieves the status of the open file, or in the static version, retrieves the status of the specified file (static, virtual function).
CFile::LockRangeLocks a range of bytes in a file.
CFile::OpenSafely opens a file with an error-testing option.
CFile::ReadReads (unbuffered) data from a file at the current file position.
CFile::RemoveDeletes the specified file (static function).
CFile::RenameRenames the specified file (static function).
CFile::SeekPositions the current file pointer.
CFile::SeekToBeginPositions the current file pointer at the beginning of the file.
CFile::SeekToEndPositions the current file pointer at the end of the file.
CFile::SetFilePathSets the full file path of the selected file.
CFile::SetLengthChanges the length of the file.
CFile::SetStatusSets the status of the specified file (static, virtual function).
CFile::UnlockRangeUnlocks a range of bytes in a file.
CFile::WriteWrites (unbuffered) data in a file to the current file position.

Public Operators

NameDescription
CFile::operator HANDLEA handle to a CFile object.

Public Data Members

NameDescription
CFile::hFileNullDetermines if the CFile object has a valid handle.
CFile::m_hFileUsually contains the operating-system file handle.

Protected Data Members

NameDescription
CFile::m_pTMPointer to CAtlTransactionManager object.

It directly provides unbuffered, binary disk input/output services, and it indirectly supports text files and memory files through its derived classes. CFile works in conjunction with the CArchive class to support serialization of Microsoft Foundation Class objects.

The hierarchical relationship between this class and its derived classes allows your program to operate on all file objects through the polymorphic CFile interface. A memory file, for example, behaves like a disk file.

Use CFile and its derived classes for general-purpose disk I/O. Use ofstream or other Microsoft iostream classes for formatted text sent to a disk file.

Normally, a disk file is opened automatically on CFile construction and closed on destruction. Static member functions permit you to interrogate a file's status without opening the file.

For more information on using CFile, see the articles Files in MFC and File Handling in the Run-Time Library Reference.

CObject

CFile

Header: afx.h

Closes the file associated with this object and makes the file unavailable for reading or writing.

virtual void Abort();

Remarks

If you have not closed the file before destroying the object, the destructor closes it for you.

When handling exceptions, CFile::Abort differs from CFile::Close in two important ways. First, the Abort function will not throw an exception on failures because failures are ignored by Abort. Second, Abort will not ASSERT if the file has not been opened or was closed previously.

If you used new to allocate the CFile object on the heap, then you must delete it after closing the file. Abort sets m_hFile to CFile::hFileNull.

Example

            CStdioFile fileTest;
            TCHAR* pszFileName = _T("Abort_File.dat");

            // do stuff that may cause exceptions
            CFileException ex;
            if (!fileTest.Open(pszFileName, CFile::modeWrite, &ex))
            {
               ex.ReportError();
               fileTest.Abort();   // close file safely and quietly
            }

Constructs and initializes a CFile object.

CFile();  
CFile(CAtlTransactionManager* pTM);  
  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

Remarks

The following five tables list the possible options for the nOpenFlags parameter.

Choose only one of the following file access mode options. The default file access mode is CFile::modeRead, which is read only.

ValueDescription
CFile::modeReadRequests read access only.
CFile::modeWriteRequests write access only.
CFile::modeReadWriteRequests read and write access.

Choose one of the following character mode options.

ValueDescription
CFile::typeBinarySets binary mode (used in derived classes only).
CFile::typeTextSets text mode with special processing for carriage return–linefeed pairs (used in derived classes only).
CFile::typeUnicodeSets Unicode mode (used in derived classes only). Text is written to the file in Unicode format when the application is built in a Unicode configuration. No BOM is written to the file.

Choose only one of the following file share mode options. The default file share mode is CFile::shareExclusive, which is exclusive.

ValueDescription
CFile::shareDenyNoneNo sharing restrictions.
CFile::shareDenyReadDenies read access to all others.
CFile::shareDenyWriteDenies write access to all others.
CFile::shareExclusiveDenies read and write access to all others.

Choose the first, or both, of the following file creation mode options. The default creation mode is CFile::modeNoTruncate, which is open existing.

ValueDescription
CFile::modeCreateCreates a new file if no file exists.; If the file already exists, CFileException is raised.
CFile::modeNoTruncateCreates a new file if no file exists; otherwise, if the file already exists, it is attached to the CFile object.

Choose the following file caching options as described. By default, the system uses a general purpose caching scheme that is not available as an option.

ValueDescription
CFile::osNoBufferThe system does not use an intermediate cache for the file. This option cancels the following 2 options.
CFile::osRandomAccessThe file cache is optimized for random access. Do not use this option and the sequential scan option.
CFile::osSequentialScanThe file cache is optimized for sequential access. Do not use this option and the random access option.
CFile::osWriteThroughWrite operations are performed without delay.

Choose the following security option to prevent the file handle from being inherited. By default, any new child processes can use the file handle.

ValueDescription
CFile::modeNoInheritPrevents any child processes from using the file handle.

The default constructor initializes members but does not attach a file to the CFile object. After using this constructor, use the CFile::Open method to open a file and attach it to the CFile object.

The constructor with one parameter initializes members and attaches an existing file to the CFile object.

The constructor with two parameters initializes members and tries to open the specified file. If this constructor successfully opens the specified file, the file is attached to the CFile object; otherwise, this constructor throws a pointer to a CInvalidArgException object. For more information about how to handle exceptions, see Exceptions.

If a CFile object successfully opens a specified file, it will close this file automatically when the CFile object is destroyed; otherwise, you must explicitly close the file after it is no longer attached to the CFile object.

Example

The following code shows how to use a CFile.

         HANDLE hFile = CreateFile(_T("CFile_File.dat"),
            GENERIC_WRITE, FILE_SHARE_READ,
            NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

         if (hFile == INVALID_HANDLE_VALUE)
         {
            AfxMessageBox(_T("Couldn't create the file!"));
         }
         else
         {
            // Attach a CFile object to the handle we have.
            CFile myFile(hFile);

            static const TCHAR sz[] = _T("I love CFile!");

            // write string
            myFile.Write(sz, sizeof(sz));

            // We need to call Close() explicitly. Note that there's no need to 
            // call CloseHandle() on the handle returned by the API because 
            // Close() automatically calls CloseHandle() for us.
            myFile.Close();

Closes the file associated with this object and makes the file unavailable for reading or writing.

virtual void Close();

Remarks

If you have not closed the file before destroying the object, the destructor closes it for you.

If you used new to allocate the CFile object on the heap, then you must delete it after closing the file. Close sets m_hFile to CFile::hFileNull.

Example

See the example for CFile::CFile.

Constructs a duplicate CFile object for a given file.

virtual CFile* Duplicate() const;  

Return Value

A pointer to a duplicate CFile object.

Remarks

This is equivalent to the C run-time function _dup.

Forces any data remaining in the file buffer to be written to the file.

virtual void Flush();

Remarks

The use of Flush does not guarantee flushing of CArchive buffers. If you are using an archive, call CArchive::Flush first.

Example

See the example for CFile::SetFilePath.

Call this member function to retrieve the name of a specified file.

virtual CString GetFileName() const;  

Return Value

The name of the file.

Remarks

For example, when you call GetFileName to generate a message to the user about the file c:\windows\write\myfile.wri, the filename, myfile.wri, is returned.

To return the entire path of the file, including the name, call GetFilePath. To return the title of the file ( myfile), call GetFileTitle.

Example

This code fragment opens the SYSTEM.INI file in your WINDOWS directory. If found, the example will print out the name and path and title, as shown under Output:

            try
            {
               // try to open the file
               CFile sysFile(_T("C:\\WINDOWS\\SYSTEM.INI"), CFile::modeRead);

               // print out path name and title information
               _tprintf_s(_T("Path is : \"%s\"\n"),
                  (LPCTSTR) sysFile.GetFilePath());
               _tprintf_s(_T("Name is : \"%s\"\n"),
                  (LPCTSTR) sysFile.GetFileName());
               _tprintf_s(_T("Title is: \"%s\"\n"), 
                  (LPCTSTR) sysFile.GetFileTitle());

               // close the file handle
               sysFile.Close();
            }
            catch (CFileException* pEx)
            {
               // if an error occurs, just make a message box
               pEx->ReportError();
               pEx->Delete();
            }

Call this member function to retrieve the full path of a specified file.

virtual CString GetFilePath() const;  

Return Value

The full path of the specified file.

Remarks

For example, when you call GetFilePath to generate a message to the user about the file c:\windows\write\myfile.wri, the file path, c:\windows\write\myfile.wri, is returned.

To return just the name of the file ( myfile.wri), call GetFileName. To return the title of the file ( myfile), call GetFileTitle.

Example

See the example for GetFileName.

Call this member function to retrieve the file title (the display name) for the file.

virtual CString GetFileTitle() const;  

Return Value

The title of the underlying file.

Remarks

This method calls GetFileTitle to retrieve the title of the file. If successful, the method returns the string that the system would use to display the file name to the user. Otherwise, the method calls PathFindFileName to retrieve the file name (including the file extension) of the underlying file. Therefore, the file extension will not always be included in the returned file title string. For more information, see GetFileTitle and PathFindFileName in the Windows SDK.

To return the entire path of the file, including the name, call GetFilePath. To return just the name of the file, call GetFileName.

Example

See the example for GetFileName.

Obtains the current logical length of the file in bytes.

virtual ULONGLONG GetLength() const;  

Return Value

The length of the file.

Example

            CFile* pFile = NULL;
            // Constructing a CFile object with this override may throw
            // a CFile exception, and won't throw any other exceptions.
            // Calling CString::Format() may throw a CMemoryException,
            // so we have a catch block for such exceptions, too. Any
            // other exception types this function throws will be
            // routed to the calling function.
            try
            {
               pFile = new CFile(_T("C:\\WINDOWS\\SYSTEM.INI"),
                  CFile::modeRead | CFile::shareDenyNone);
               ULONGLONG dwLength = pFile->GetLength();
               CString str;
               str.Format(_T("Your SYSTEM.INI file is %I64u bytes long."), dwLength);
               AfxMessageBox(str);
            }
            catch (CFileException* pEx)
            {
               // Simply show an error message to the user.
               pEx->ReportError();
               pEx->Delete();
            }
            catch(CMemoryException* pEx)
            {
               pEx->ReportError();
               pEx->Delete();
               // We can't recover from this memory exception, so we'll
               // just terminate the app without any cleanup. Normally,
               // an application should do everything it possibly can to
               // clean up properly and _not_ call AfxAbort().
               AfxAbort();
            }

            // If an exception occurs in the CFile constructor,
            // the language will free the memory allocated by new
            // and will not complete the assignment to pFile.
            // Thus, our clean-up code needs to test for NULL.
            if (pFile != NULL)
            {
               pFile->Close();
               delete pFile;
            }         

Obtains the current value of the file pointer, which can be used in subsequent calls to Seek.

virtual ULONGLONG GetPosition() const;  

Return Value

The file pointer.

Example

            CFile cfile;
            cfile.Open(_T("Seek_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            LONGLONG lOffset = 1000;
            ULONGLONG lActual;
            lActual = cfile.Seek(lOffset, CFile::begin);
            ASSERT(cfile.GetPosition() == lActual);

This method retrieves status information related to a given CFile object instance or a given file path.

BOOL GetStatus(CFileStatus& rStatus) const;  
  
static BOOL PASCAL GetStatus(
    LPCTSTR lpszFileName,  
    CFileStatus& rStatus,
    CAtlTransactionManager* pTM = NULL);

Parameters

rStatus
A reference to a user-supplied CFileStatus structure that will receive the status information. The CFileStatus structure has the following fields:

  • CTime m_ctime The date and time the file was created.

  • CTime m_mtime The date and time the file was last modified.

  • CTime m_atime The date and time the file was last accessed for reading.

  • ULONGLONG m_size The logical size of the file in bytes, as reported by the DIR command.

  • BYTE m_attribute The attribute byte of the file.

  • char m_szFullName[_MAX_PATH] The absolute filename in the Windows character set.

lpszFileName
A string in the Windows character set that is the path to the desired file. The path can be relative or absolute, or it can contain a network path name.

pTM
Pointer to CAtlTransactionManager object

Return Value

TRUE if the status information for the specified file is successfully obtained; otherwise, FALSE.

Remarks

The non-static version of GetStatus retrieves status information of the open file associated with the given CFile object. The static version of GetStatus obtains the file status from a given file path without actually opening the file. This is useful for testing the existence and access rights of a file.

The m_attribute member of the CFileStatus structure refers to the file attribute set. The CFile class provides the Attribute enumeration type so file attributes can be specified symbolically:

enum Attribute {

normal = 0x00,

readOnly = 0x01,

hidden = 0x02,

system = 0x04,

volume = 0x08,

directory = 0x10,

archive = 0x20

};

Example

            CFile cfile;
            cfile.Open(_T("SetLength_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            ULONGLONG dwNewLength = 10000;
            cfile.SetLength(dwNewLength);
            CFileStatus status;
            if(cfile.GetStatus(status))    // virtual member function
            {
               TRACE(_T("File size = %u\n"), status.m_size);
            }
            TCHAR* pszFileName = _T("SetLength_File.dat");
            if(CFile::GetStatus(pszFileName, status))   // static function
            {
               TRACE(_T("Full file name = %s\n"), status.m_szFullName);
            }

Determines the presence of a valid file handle for the CFile object.

static AFX_DATA const HANDLE hFileNull;  

Remarks

This constant is used to determine if the CFile object has a valid file handle.

The following example demonstrates this operation:

            if (myFile.m_hFile != CFile::hFileNull)
               ;//perform operations on the file
            else
               ;//indicate the presence of an invalid handle         

Locks a range of bytes in an open file, throwing an exception if the file is already locked.

virtual void LockRange(
    ULONGLONG dwPos,  
    ULONGLONG dwCount);

Parameters

dwPos
The byte offset of the start of the byte range to lock.

dwCount
The number of bytes in the range to lock.

Remarks

Locking bytes in a file prevents access to those bytes by other processes. You can lock more than one region of a file, but no overlapping regions are allowed.

When you unlock the region, using the UnlockRange member function, the byte range must correspond exactly to the region that was previously locked. The LockRange function does not merge adjacent regions; if two locked regions are adjacent, you must unlock each region separately.

System_CAPS_ICON_note.jpg Note

This function is not available for the CMemFile-derived class.

Example

            CFile cfile;
            cfile.Open(_T("LockRange_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            ULONGLONG dwPos = 10;
            ULONGLONG dwCount = 100;
            cfile.LockRange(dwPos, dwCount);

            // do something with the file

            cfile.UnlockRange(dwPos, dwCount);

Contains the operating-system file handle for an open file.

HANDLE m_hFile;  

Remarks

m_hFile is a public variable of type UINT. It contains CFile::hFileNull (an operating-system-independent empty file indicator) if the handle has not been assigned.

Use of m_hFile is not recommended because the member's meaning depends on the derived class. m_hFile is made a public member for convenience in supporting nonpolymorphic use of the class.

Pointer to a CAtlTransactionManager object.

CAtlTransactionManager* m_pTM;  

Remarks

Overloaded. Open is designed for use with the default CFile constructor.

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

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

Parameters

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

nOpenFlags
A UINT that defines the file's sharing and access mode. It specifies the action to take when opening the file. You can combine options by using the bitwise-OR ( | ) operator. One access permission and one share option are required; the modeCreate and modeNoInherit modes are optional. See the CFile constructor for a list of mode options.

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.

Remarks

The two functions form a "safe" method for opening a file where a failure is a normal, expected condition.

While the CFile constructor will throw an exception in an error condition, Open will return FALSE for error conditions. Open can still initialize a CFileException object to describe the error, however. If you don't supply the pError parameter, or if you pass NULL for pError, Open will return FALSE and not throw a CFileException. If you pass a pointer to an existing CFileException, and Open encounters an error, the function will fill it with information describing that error. In neither case will Open throw an exception.

The following table describes the possible results of Open.

pErrorError encounteredReturn valueCFileException content
NULLNoTRUEn/a
ptr to CFileExceptionNoTRUEunchanged
NULLYesFALSEn/a
ptr to CFileExceptionYesFALSEinitialized to describe error

Example

            CFile f;
            CFileException e;
            TCHAR* pszFileName = _T("Open_File.dat");
            if(!f.Open(pszFileName, CFile::modeCreate | CFile::modeWrite, &e))
            {
               TRACE(_T("File could not be opened %d\n"), e.m_cause);
            }

//A second example for CFile::Open.
//This function uses CFile to copy binary files.
bool BinaryFileCopy(LPCTSTR pszSource, LPCTSTR pszDest)
{
   // constructing these file objects doesn't open them
   CFile sourceFile;
   CFile destFile;

   // we'll use a CFileException object to get error information
   CFileException ex;

   // open the source file for reading
   if (!sourceFile.Open(pszSource,
      CFile::modeRead | CFile::shareDenyWrite, &ex))
   {
      // complain if an error happened
      // no need to delete the ex object

      TCHAR szError[1024];
      ex.GetErrorMessage(szError, 1024);
      _tprintf_s(_T("Couldn't open source file: %1024s"), szError);
      return false;
   }
   else
   {
      if (!destFile.Open(pszDest, CFile::modeWrite |
         CFile::shareExclusive | CFile::modeCreate, &ex))
      {
         TCHAR szError[1024];
         ex.GetErrorMessage(szError, 1024);
         _tprintf_s(_T("Couldn't open source file: %1024s"), szError);

         sourceFile.Close();
         return false;
      }

      BYTE buffer[4096];
      DWORD dwRead;

      // Read in 4096-byte blocks,
      // remember how many bytes were actually read,
      // and try to write that many out. This loop ends
      // when there are no more bytes to read.
      do
      {
         dwRead = sourceFile.Read(buffer, 4096);
         destFile.Write(buffer, dwRead);
      }
      while (dwRead > 0);

      // Close both files

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

   return true;
}

Use this operator to pass a handle to a CFile object to functions such as ReadFileEx and GetFileTime that expect a HANDLE.

operator HANDLE() const;  

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

virtual UINT Read(
    void* lpBuf,  
    UINT nCount);

Parameters

lpBuf
Pointer to the user-supplied buffer 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–linefeed pairs are counted as single characters.

Return Value

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

Example

            CFile cfile;
            cfile.Open(_T("Write_File.dat"), CFile::modeCreate | 
               CFile::modeReadWrite);
            char pbufWrite[100];
            memset(pbufWrite, 'a', sizeof(pbufWrite));
            cfile.Write(pbufWrite, 100);         
            cfile.Flush();
            cfile.SeekToBegin();
            char pbufRead[100];
            cfile.Read(pbufRead, sizeof(pbufRead));
            ASSERT(0 == memcmp(pbufWrite, pbufRead, sizeof(pbufWrite)));

For another example see CFile::Open.

This static function deletes the file specified by the path.

static void PASCAL Remove(
    LPCTSTR lpszFileName, 
    CAtlTransactionManager* pTM = NULL);

Parameters

lpszFileName
A string that is the path to the desired file. The path can be relative or absolute, and can contain a network name.

pTM
Pointer to CAtlTransactionManager object

Remarks

It will not remove a directory.

The Remove member function throws an exception if the connected file is open or if the file cannot be removed. This is equivalent to the DEL command.

Example

            //example for CFile::Remove
            TCHAR* pFileName = _T("Remove_File.dat");
            try
            {
               CFile::Remove(pFileName);
            }
            catch (CFileException* pEx)
            {
               TRACE(_T("File %20s cannot be removed\n"), pFileName);
               pEx->Delete();
            }

This static function renames the specified file.

static void PASCAL Rename(
    LPCTSTR lpszOldName,  
    LPCTSTR lpszNewName,  
    CAtlTransactionManager* pTM = NULL);

Parameters

lpszOldName
The old path.

lpszNewName
The new path.

pTM
Pointer to CAtlTransactionManager object

Remarks

Directories cannot be renamed. This is equivalent to the REN command.

Example

            TCHAR* pOldName = _T("Oldname_File.dat");
            TCHAR* pNewName = _T("Renamed_File.dat");

            try
            {
                CFile::Rename(pOldName, pNewName);
            }
            catch(CFileException* pEx )
            {
                TRACE(_T("File %20s not found, cause = %d\n"), pOldName, 
                   pEx->m_cause);
                pEx->Delete();
            }

Repositions the file pointer in an open file.

virtual ULONGLONG Seek(
LONGLONG lOff,  
UINT nFrom);

Parameters

lOff
Number of bytes to move the file pointer. Positive values move the file pointer towards the end of the file; negative values move the file pointer towards the start of the file.

nFrom
Position to seek from. See the Remarks section for possible values.

Return Value

The position of the file pointer if the method was successful; otherwise, the return value is undefined and a pointer to a CFileException exception is thrown.

Remarks

The following table lists possible values for the nFrom parameter.

ValueDescription
CFile::beginSeek from the start of the file.
CFile::currentSeek from the current location of the file pointer.
CFile::endSeek from the end of the file.

When a file is opened, the file pointer is positioned at 0, the start of the file.

You can set the file pointer to a position beyond the end of a file. If you do this, the size of the file does not increase until you write to the file.

The exception handler for this method must delete the exception object after the exception is processed.

Example

            CFile cfile;
            cfile.Open(_T("Seek_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            LONGLONG lOffset = 1000;
            ULONGLONG lActual;
            lActual = cfile.Seek(lOffset, CFile::begin);

Sets the value of the file pointer to the beginning of the file.

void SeekToBegin();

Remarks

SeekToBegin() is equivalent to Seek( 0L, CFile::begin ).

Example

            CFile f;
            f.Open(_T("Seeker_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            f.SeekToBegin();
            ULONGLONG ullEnd = f.SeekToEnd();

Sets the value of the file pointer to the logical end of the file.

ULONGLONG SeekToEnd();

Return Value

The length of the file in bytes.

Remarks

SeekToEnd() is equivalent to CFile::Seek( 0L, CFile::end ).

Example

            CFile f;
            f.Open(_T("Seeker_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            f.SeekToBegin();
            ULONGLONG ullEnd = f.SeekToEnd();

Call this function to specify the path of the file; for example, if the path of a file is not available when a CFile object is constructed, call SetFilePath to provide it.

virtual void SetFilePath(LPCTSTR lpszNewName);

Parameters

lpszNewName
Pointer to a string specifying the new path.

Remarks

System_CAPS_ICON_note.jpg Note

SetFilePath does not open the file or create the file; it simply associates the CFile object with a path name, which can then be used.

Example

            TCHAR* pstrName = _T("C:\\test\\SetPath_File.dat");

            // open a file
            HANDLE hFile = ::CreateFile(pstrName, GENERIC_WRITE, FILE_SHARE_READ,
               NULL, CREATE_ALWAYS, 0, NULL);

            if (hFile != INVALID_HANDLE_VALUE)
            {
               // attach a CFile object to it
               CFile myFile(hFile);

               // At this point, myFile doesn't know the path name for the file
               // it owns because Windows doesn't associate that information
               // with the handle. Any CFileExceptions thrown by this object
               // won't have complete information.

               // Calling SetFilePath() remedies that problem by letting CFile
               // know the name of the file that's associated with the object.

               myFile.SetFilePath(pstrName);

               // write something to the file and flush it immediately
               DWORD dwValue = 1234;
               myFile.Write(&dwValue, sizeof(dwValue));
               myFile.Flush();

               // destroying the CObject here will call ::CloseHandle() on the file
            } 

Call this function to change the length of the file.

virtual void SetLength(ULONGLONG dwNewLen);

Parameters

dwNewLen
Desired length of the file in bytes. This value can be larger or smaller than the current length of the file. The file will be extended or truncated as appropriate.

Remarks

System_CAPS_ICON_note.jpg Note

With CMemFile, this function could throw a CMemoryException object.

Example

            CFile cfile;
            cfile.Open(_T("SetLength_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            ULONGLONG dwNewLength = 10000;
            cfile.SetLength(dwNewLength);

Sets the status of the file associated with this file location.

static void PASCAL SetStatus(
    LPCTSTR lpszFileName,  
    const CFileStatus& status,  
    CAtlTransactionManager* pTM = NULL);

Parameters

lpszFileName
A string that is the path to the desired file. The path can be relative or absolute, and can contain a network name.

status
The buffer containing the new status information. Call the GetStatus member function to prefill the CFileStatus structure with current values, then make changes as required. If a value is 0, then the corresponding status item is not updated. See the GetStatus member function for a description of the CFileStatus structure.

pTM
Pointer to CAtlTransactionManager object

Remarks

To set the time, modify the m_mtime field of status.

Please note that when you make a call to SetStatus in an attempt to change only the attributes of the file, and the m_mtime member of the file status structure is nonzero, the attributes may also be affected (changing the time stamp may have side effects on the attributes). If you want to only change the attributes of the file, first set the m_mtime member of the file status structure to zero and then make a call to SetStatus.

Example

            TCHAR* pFileName = _T("ReadOnly_File.dat");
            CFileStatus status;
            CFile::GetStatus(pFileName, status);
            status.m_attribute |= CFile::readOnly;
            CFile::SetStatus(pFileName, status);         

Unlocks a range of bytes in an open file.

virtual void UnlockRange(
    ULONGLONG dwPos,  
    ULONGLONG dwCount);

Parameters

dwPos
The byte offset of the start of the byte range to unlock.

dwCount
The number of bytes in the range to unlock.

Remarks

See the description of the LockRange member function for details.

System_CAPS_ICON_note.jpg Note

This function is not available for the CMemFile-derived class.

Example

            CFile cfile;
            cfile.Open(_T("LockRange_File.dat"), CFile::modeCreate |
               CFile::modeReadWrite);
            ULONGLONG dwPos = 10;
            ULONGLONG dwCount = 100;
            cfile.LockRange(dwPos, dwCount);

            // do something with the file

            cfile.UnlockRange(dwPos, dwCount);

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

virtual void Write(
    const void* lpBuf,  
    UINT nCount);

Parameters

lpBuf
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–linefeed pairs are counted as single characters.

Remarks

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

Example

            CFile cfile;
            cfile.Open(_T("Write_File.dat"), CFile::modeCreate | 
               CFile::modeReadWrite);
            char pbufWrite[100];
            memset(pbufWrite, 'a', sizeof(pbufWrite));
            cfile.Write(pbufWrite, 100);         
            cfile.Flush();

In addition, see the examples for CFile::CFile and CFile::Open.

MFC Sample DRAWCLI
CObject Class
Hierarchy Chart
CStdioFile Class
CMemFile Class

Show: