title | ms.custom | ms.date | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | f1_keywords | dev_langs | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CFile Class | Microsoft Docs |
11/04/2016 |
|
reference |
|
|
|
b2eb5757-d499-4e67-b044-dd7d1abaa0f8 |
22 |
mikeblome |
mblome |
ghogen |
The base class for Microsoft Foundation Class file classes.
class CFile : public CObject
Name | Description |
---|---|
CFile::CFile | Constructs a CFile object from a path or file handle. |
Name | Description |
---|---|
CFile::Abort | Closes a file ignoring all warnings and errors. |
CFile::Close | Closes a file and deletes the object. |
CFile::Duplicate | Constructs a duplicate object based on this file. |
CFile::Flush | Flushes any data yet to be written. |
CFile::GetFileName | Retrieves the filename of the selected file. |
CFile::GetFilePath | Retrieves the full file path of the selected file. |
CFile::GetFileTitle | Retrieves the title of the selected file. |
CFile::GetLength | Retrieves the length of the file. |
CFile::GetPosition | Retrieves the current file pointer. |
CFile::GetStatus | Retrieves the status of the open file, or in the static version, retrieves the status of the specified file (static, virtual function). |
CFile::LockRange | Locks a range of bytes in a file. |
CFile::Open | Safely opens a file with an error-testing option. |
CFile::Read | Reads (unbuffered) data from a file at the current file position. |
CFile::Remove | Deletes the specified file (static function). |
CFile::Rename | Renames the specified file (static function). |
CFile::Seek | Positions the current file pointer. |
CFile::SeekToBegin | Positions the current file pointer at the beginning of the file. |
CFile::SeekToEnd | Positions the current file pointer at the end of the file. |
CFile::SetFilePath | Sets the full file path of the selected file. |
CFile::SetLength | Changes the length of the file. |
CFile::SetStatus | Sets the status of the specified file (static, virtual function). |
CFile::UnlockRange | Unlocks a range of bytes in a file. |
CFile::Write | Writes (unbuffered) data in a file to the current file position. |
Name | Description |
---|---|
CFile::operator HANDLE | A handle to a CFile object. |
Name | Description |
---|---|
CFile::hFileNull | Determines if the CFile object has a valid handle. |
CFile::m_hFile | Usually contains the operating-system file handle. |
Name | Description |
---|---|
CFile::m_pTM | Pointer 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.
CFile
Header: afx.h
Closes the file associated with this object and makes the file unavailable for reading or writing.
virtual void Abort();
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
.
[!code-cppNVC_MFCFiles#5]
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);
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
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.
Value | Description |
---|---|
CFile::modeRead |
Requests read access only. |
CFile::modeWrite |
Requests write access only. |
CFile::modeReadWrite |
Requests read and write access. |
Choose one of the following character mode options.
Value | Description |
---|---|
CFile::typeBinary |
Sets binary mode (used in derived classes only). |
CFile::typeText |
Sets text mode with special processing for carriage return-linefeed pairs (used in derived classes only). |
CFile::typeUnicode |
Sets 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.
Value | Description |
---|---|
CFile::shareDenyNone |
No sharing restrictions. |
CFile::shareDenyRead |
Denies read access to all others. |
CFile::shareDenyWrite |
Denies write access to all others. |
CFile::shareExclusive |
Denies 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.
Value | Description |
---|---|
CFile::modeCreate |
Creates a new file if no file exists.; If the file already exists, CFileException is raised. |
CFile::modeNoTruncate |
Creates 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.
Value | Description |
---|---|
CFile::osNoBuffer |
The system does not use an intermediate cache for the file. This option cancels the following 2 options. |
CFile::osRandomAccess |
The file cache is optimized for random access. Do not use this option and the sequential scan option. |
CFile::osSequentialScan |
The file cache is optimized for sequential access. Do not use this option and the random access option. |
CFile::osWriteThrough |
Write 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.
Value | Description |
---|---|
CFile::modeNoInherit |
Prevents 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.
The following code shows how to use a CFile
.
[!code-cppNVC_MFCFiles#4]
Closes the file associated with this object and makes the file unavailable for reading or writing.
virtual void Close();
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
.
See the example for CFile::CFile.
Constructs a duplicate CFile
object for a given file.
virtual CFile* Duplicate() const;
A pointer to a duplicate CFile
object.
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();
The use of Flush
does not guarantee flushing of CArchive
buffers. If you are using an archive, call CArchive::Flush first.
See the example for CFile::SetFilePath.
Call this member function to retrieve the name of a specified file.
virtual CString GetFileName() const;
The name of the file.
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.
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:
[!code-cppNVC_MFCFiles#6]
Call this member function to retrieve the full path of a specified file.
virtual CString GetFilePath() const;
The full path of the specified file.
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.
See the example for GetFileName.
Call this member function to retrieve the file title (the display name) for the file.
virtual CString GetFileTitle() const;
The title of the underlying file.
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.
See the example for GetFileName.
Obtains the current logical length of the file in bytes.
virtual ULONGLONG GetLength() const;
The length of the file.
[!code-cppNVC_MFCFiles#7]
Obtains the current value of the file pointer, which can be used in subsequent calls to Seek
.
virtual ULONGLONG GetPosition() const;
The file pointer.
[!code-cppNVC_MFCFiles#8]
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);
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
TRUE if the status information for the specified file is successfully obtained; otherwise, FALSE.
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
};
[!code-cppNVC_MFCFiles#10]
Determines the presence of a valid file handle for the CFile
object.
static AFX_DATA const HANDLE hFileNull;
This constant is used to determine if the CFile
object has a valid file handle.
The following example demonstrates this operation:
[!code-cppNVC_MFCFiles#22]
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);
dwPos
The byte offset of the start of the byte range to lock.
dwCount
The number of bytes in the range to lock.
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.
Note
This function is not available for the CMemFile
-derived class.
[!code-cppNVC_MFCFiles#12]
Contains the operating-system file handle for an open file.
HANDLE m_hFile;
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;
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);
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
Nonzero if the open was successful; otherwise 0. The pError
parameter is meaningful only if 0 is returned.
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.
pError |
Error encountered | Return value | CFileException content |
---|---|---|---|
NULL | No | TRUE | n/a |
ptr to CFileException |
No | TRUE | unchanged |
NULL | Yes | FALSE | n/a |
ptr to CFileException |
Yes | FALSE | initialized to describe error |
[!code-cppNVC_MFCFiles#13]
[!code-cppNVC_MFCFiles#14]
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);
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.
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.
[!code-cppNVC_MFCFiles#15]
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);
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
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.
[!code-cppNVC_MFCFiles#17]
This static function renames the specified file.
static void PASCAL Rename(
LPCTSTR lpszOldName,
LPCTSTR lpszNewName,
CAtlTransactionManager* pTM = NULL);
lpszOldName
The old path.
lpszNewName
The new path.
pTM
Pointer to CAtlTransactionManager object
Directories cannot be renamed. This is equivalent to the REN command.
[!code-cppNVC_MFCFiles#18]
Repositions the file pointer in an open file.
virtual ULONGLONG Seek(
LONGLONG lOff,
UINT nFrom);
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.
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.
The following table lists possible values for the nFrom
parameter.
Value | Description |
---|---|
CFile::begin |
Seek from the start of the file. |
CFile::current |
Seek from the current location of the file pointer. |
CFile::end |
Seek 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.
[!code-cppNVC_MFCFiles#9]
Sets the value of the file pointer to the beginning of the file.
void SeekToBegin();
SeekToBegin()
is equivalent to Seek( 0L, CFile::begin )
.
[!code-cppNVC_MFCFiles#19]
Sets the value of the file pointer to the logical end of the file.
ULONGLONG SeekToEnd();
The length of the file in bytes.
SeekToEnd()
is equivalent to CFile::Seek( 0L, CFile::end )
.
[!code-cppNVC_MFCFiles#19]
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);
lpszNewName
Pointer to a string specifying the new path.
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.
[!code-cppNVC_MFCFiles#20]
Call this function to change the length of the file.
virtual void SetLength(ULONGLONG dwNewLen);
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.
Note
With CMemFile
, this function could throw a CMemoryException
object.
[!code-cppNVC_MFCFiles#11]
Sets the status of the file associated with this file location.
static void PASCAL SetStatus(
LPCTSTR lpszFileName,
const CFileStatus& status,
CAtlTransactionManager* pTM = NULL);
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
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
.
[!code-cppNVC_MFCFiles#21]
Unlocks a range of bytes in an open file.
virtual void UnlockRange(
ULONGLONG dwPos,
ULONGLONG dwCount);
dwPos
The byte offset of the start of the byte range to unlock.
dwCount
The number of bytes in the range to unlock.
See the description of the LockRange member function for details.
Note
This function is not available for the CMemFile
-derived class.
[!code-cppNVC_MFCFiles#12]
Writes data from a buffer to the file associated with the CFile
object.
virtual void Write(
const void* lpBuf,
UINT nCount);
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.
Write throws an exception in response to several conditions, including the disk-full condition.
[!code-cppNVC_MFCFiles#16]
In addition, see the examples for CFile::CFile and CFile::Open.
MFC Sample DRAWCLI
CObject Class
Hierarchy Chart
CStdioFile Class
CMemFile Class