Use of CFile

Source: Internet
Author: User
Tags access properties flush

File processing is a major play in the program, mainly using CFile and CArchive and their derived classes.

CFile:

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.

For non-cached binary disk input its derived classes can be used for text files and memory files

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.

Hard disk files can be automatically turned on or off through constructors and destructors to get the state of the file by calling the static member function without opening the file.

The member functions are:

Cflie () Open () Close () Read () Write () Flush () GetLength () Seek () Seektobegin () Seektoend () GetLength ()

GetFileName () GetFilePath () GetFileTitle () GetStatus () ReName ()

Open it:

The constructor opens:

CFile (
HANDLE hfile
);
CFile (
LPCTSTR lpszFileName,
UINT Nopenflags
);

EX (MSDN):


1 HANDLE hfile = CreateFile (_t ("Cfile_file.dat"),
2 Generic_write, File_share_read,
3 null, create_always, file_attribute_normal, NULL);
4
5 if (hfile = = INVALID_HANDLE_VALUE)
6 {
7 AfxMessageBox (_t ("couldn ' T create the file!"));
8}
9 Else
10 {
One//Attach a CFile object to the handle we have.
CFile MyFile (hfile);
13
The static const TCHAR sz[] = _t ("I love cfile!");
15
+//write String
Myfile.write (SZ, sizeof (SZ));
18
//We can call Close () explicitly, but the destructor would has
//also closed the file for us. Note that there's no need to
//Call the CloseHandle () on the handle returned by the API because
//MFC would close it for us.
Myfile.close ();

member function Open:

Virtual BOOL Open (
LPCTSTR lpszFileName,
UINT Nopenflags,
cfileexception* perror = NULL
);
Two-Step walk:
1. Create an object to open the file, usually declaring an CFile or an object of a CFile derived class.

2. Call the Open method of the CFile object and provide a file path and open as a parameter to the opening method.
EX (on MSDN):

1 CFile F;
2 CFileException E;
3 tchar* pszfilename = _t ("Open_file.dat");
4 if (!f.open (pszFileName, Cfile::modecreate | Cfile::modewrite, &e))
5 {
6 TRACE (_t ("File could not being opened%d\n"), E.m_cause);
7}

View Code

1//a second example for CFile::Open.
2//this function uses CFile to copy binary files.
3 bool Binaryfilecopy (LPCTSTR Pszsource, LPCTSTR pszdest)
4 {
5//Constructing these file objects doesn ' t open them
6 CFile sourcefile;
7 CFile DestFile;
8
9//We ll use a CFileException object to get error information
Ten CFileException ex;
11
//Open the source file for reading
if (!sourcefile.open (Pszsource,
Cfile::moderead | Cfile::sharedenywrite, &ex))
15 {
+//complain if an error happened
/No need to delete the ex object
18
TCHAR szerror[1024];
Ex. GetErrorMessage (szerror, 1024);
_tprintf_s (_t ("couldn ' T open source file:%1024s"), szerror);
return false;
23}
-Else
25 {
if (!destfile.open (Pszdest, Cfile::modewrite |
cfile::shareexclusive | Cfile::modecreate, &ex))
28 {
TCHAR szerror[1024];
The ex. GetErrorMessage (szerror, 1024);
_tprintf_s (_t ("couldn ' T open source file:%1024s"), szerror);
32
Sourcefile.close ();
return false;
35}
36
Notoginseng BYTE buffer[4096];
Dwread DWORD;
39
+//Read in 4096-byte blocks,
Remember how many bytes were actually read,
Many//and try to write that is out. This loop ends
When there is no more bytes to read.
Do
45 {
Dwread = sourcefile.read (buffer, 4096);
Destfile.write (buffer, dwread);
48}
(Dwread > 0);
50
Wuyi//Close both files
52
Destfile.close ();
Sourcefile.close ();
55}
56
The return true;
58}

Open the sharing and Access properties settings:

Cfile::modecreate directly constructs to create a new file if this file exists, then delete everything in the file.

Cfile::modenotruncate Union creates a property, and if the file is created, the original file content is not deleted, so the file can be opened as a newly created file that already exists or does not exist. This is very meaningful, for example, to open a file that is either present or nonexistent. This property is also very good for cstdiofile.
Cfile::moderead opens as a read-only property.
Cfile::modewrite Open as write-only property.
Cfile::modereadwrite Open as read-write property.
Cfile::modenoinherit prevent this file from being a child process.
Cfile::sharedenynone Open this file outside of this file read and write processing
Cfile::sharedenyread Open in exclusive mode, rejecting other read operations
Cfile::sharedenywrite Open in exclusive mode, rejecting other write operations
Cfile::shareexclusive opens the file exclusively, denying other read and write operations access to this file opens the document with exclusive mode, denying other if the file is open for read-write operation the construction fails
Cfile::sharecompat This attribute is not available in the-bit MFC. This flag maps to cfile::shareexclusive when applied to CFile::Open.
Cfile::typetext Set Text mode specifically handles carriage return line (used in derived classes only).
Cfile::typebinary set binary mode (used in derived classes only).

The class CStdioFile that is commonly used to read and write strings from a file is derived from CFile, so objects of the CStdioFile class can also open an object directly by calling the Open method, see the following example:

CString Csext;
CStdioFile Rfile (_t ("C:\\myfiles\\myfile1.txt"), Cfile::moderead); Defines and initializes a pair of rfile for a CStdioFile class
A line-by-line read-in string
while (Rfile.readstring (Csext))
{
TRACE (_t ("%s\n"), Csext);
}
Rfile.close ();

Read the file:
Virtual UINT Read (
Void* Lpbuf,
UINT ncount
);
LPBUF: The user-specified buffer pointer to store the read content

Ncount: Specifies the maximum number of bytes to read and write
Returns the number of bytes actually read when EOF is encountered, less than ncount
EX (MSDN):
View Code

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)));

Write files: (preferably using try...catch ... Blocks to catch errors)

virtual void Write (
Const void* LPBUF,
UINT ncount
);
LPBUF: The buffer that points to the data to be written
Ncount: Number of bytes to write
no return value.
EX (MSDN):
View Code

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 ();

Flush () function:

virtual void Flush ();
Forces any data remaining in the file, buffer to is written to the file.

Writes the data in the file buffer into a file, typically calling the following flush function after calling the Write function

EX (MSDN):

View Code

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 has 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 would call:: CloseHandle () on the file
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.