Cfile Operation Details
A variety of file operations are very common in program design. If you know all of their operations well, you can find the best solution based on the actual situation, writing efficient code in a short period of time, so it is very important to master file operations. This article will give a comprehensive introduction to file operations in Visual C ++, and conduct a detailed analysis of some difficult problems frequently encountered in file operations.
1. File Search
When operating on a file, if you do not know whether the file exists, you must first find it. There is a class cfilefind specifically used for file search in MFC, which can be used to conveniently and quickly find files. The following code demonstrates the most basic usage of this class.
Cstring strfiletitle;
Cfilefind finder;
Bool bworking = finder. findfile ("C: // windows // sysbkup // *. Cab ");
While (bworking)
{
Bworking = finder. findnextfile ();
Strfiletitle = finder. getfiletitle ();
}
2. File opening/saving dialog box
The file open/save dialog box is used when users select to open and store files. The cfiledialog class of MFC is used to implement this function. When cfiledialog is used to declare an object, the first bool parameter is used to specify whether to open or save the file. If it is set to true, a file opening dialog box is created. If it is set to false, a file saving dialog box is created.
When constructing a cfilediect object, if the ofn_allowmultiselect style is specified in the parameter, you can select multiple items in this dialog box. In this case, pay attention to allocating a piece of memory to m_ofn.lpstrfile of the cfiledialog object to store the names of all the file paths returned by the multiple-choice operation. If no allocation is made or the allocated memory is too small, the Operation will fail. The following program demonstrates how to use the file opening dialog box.
Cfiledialog mfiledlg (true, null, null,
Ofn_hidereadonly | ofn_overwriteprompt | ofn_allowmultiselect,
"All files (*. *) | *. * |", afxgetmainwnd ());
Cstring STR ("", 10000 );
Mfiledlg. m_ofn.lpstrfile = Str. getbuffer (1, 10000 );
Str. releasebuffer ();
Position MPOs = mfiledlg. getstartposition ();
Cstring pathname ("", 128 );
Cfilestatus status;
While (MPOs! = NULL)
{
Pathname = mfiledlg. getnextpathname (MPOs );
Cfile: getstatus (pathname, status );
}
3. file read/write
The reading and writing of files is very important. The following sections will focus on the introduction. The most common way to read and write files is to directly use cfile. For example, you can use the following method to read and write files:
// Read the object
Char sread [2];
Cfile mfile (_ T ("user.txt"), cfile: moderead );
If (mfile. getlength () <2)
Return;
Mfile. Read (sread, 2 );
Mfile. Close ();
// Write the object
Cfile mfile (_ T ("user.txt"), cfile: modewrite | cfile: modecreate );
Mfile. Write (sread, 2 );
Mfile. Flush ();
Mfile. Close ();
Although this method is the most basic, It is cumbersome to use and has very simple functions. I recommend using carchive, which is simple and powerful. First, you should declare an object with cfile, and then use the pointer of this object as a parameter to declare a carchive object, so that you can easily store various complex data types. See the following example.
// Write the object
Cstring strtemp;
Cfile mfile;
Mfile. Open ("D: // dd // try. Try", cfile: modecreate | cfile: modenotruncate | cfile: modewrite );
Carchive AR (& mfile, carchive: Store );
Ar <ar. Close ();
Mfile. Close ();
// Read the object
Cfile mfile;
If (mfile. Open ("D: // dd // try. Try", cfile: moderead) = 0)
Return;
Carchive AR (& mfile, carchive: load );
Ar> strtemp;
Ar. Close ();
Mfile. Close ();
The <and> operators of carchive are used for reading and writing simple data types. For the access to objects of the cobject derived class, readobject () and writeobject () are used (). The readclass () and writeclass () of carchive can also be used to read and write classes, such:
// Store the caboutdlg class
Ar. writeclass (runtime_class (caboutdlg ));
// Read the caboutdlg class
Cruntimeclass * mrunclass = ar. readclass ();
// Use the caboutdlg class
Cobject * pobject = mrunclass-> Createobject ();
(Cdialog *) pobject)-> domodal ();
Although the documents/visual structures provided by VC can perform these operations, they are not easy to understand, use, and manage, therefore, although many VC entry books spend a lot of time describing documents/visual structures, I suggest you do not use their documents. There are many books on how to separate documents/views, including the well-known visual c ++ technology insider.
If the file operation you want to perform is a simple string for reading and writing the entire line, we recommend that you use cstdiofile to perform such operations conveniently, as shown in the following example.
Cstdiofile mfile;
Cfileexception m0000t;
Mfile. Open ("D: // temp // AA. Bat", cfile: modewrite, & mworkflow t );
Cstring string = "I Am a string .";
Mfile. writestring (string );
Mfile. Close ();
4. Use of temporary files
Regular software often uses temporary files. You can often see a large number of files with the TMP extension under the C:/Windows/TEMP directory. These files are temporary files created by the program running. The usage of temporary files is basically the same as that of conventional files, but the file name should be obtained by calling the gettempfilename () function. The first parameter is the path of the temporary file, the second parameter is the prefix of the temporary file name, and the fourth parameter is used to obtain the temporary file name. After obtaining the temporary file name, you can use it to create and operate the file, for example:
Char sztemppath [_ max_path], sztempfile [_ max_path];
Gettemppath (_ max_path, sztemppath );
Gettempfilename (sztemppath, _ T ("My _"), 0, sztempfile );
Cfile m_tempfile (sztempfile, cfile: modecreate | cfile: modewrite );
Char m_char = 'a ';
M_tempfile.write (& m_char, 2 );
M_tempfile.close ();
5. Copy and delete files
MFC does not provide the function of directly performing these operations, so you need to use the SDK. Commonly used file-related functions in the SDK include copyfile (), createdirectory (), deletefile (), and movefile (). Their usage is simple. For details, refer to msdn.
1. Determine whether the file exists
Access (filename, mode );
2. For file operations with different purposes, the API function createfile () is also a useful method for processing. For most of the other top-level operations that are suitable for giant files, no.
[1] display dialog box, get the file name
Cstring filepathname;
Cfiledialog DLG (true); // if the value is true, the open dialog box is displayed. If the value is false, the S *** e As dialog box is displayed.
If (DLG. domodal () = idok)
Filepathname = DLG. getpathname ();
Related information: Several member functions used by cfiledialog to retrieve file names:
Assume that the selected file is C:/Windows/test. EXE.
Then (1) getpathname (); takes the full name of the file name, including the complete path. Retrieve C:/Windows/test. exe
(2) getfiletitle (); get the full name of the file: Test. exe
(3) getfilename (); Retrieve Test
(4) getfileext (); obtain the extension exe
[2] opening a file
Cfile file ("C:/Hello. txt", cfile: moderead); // read-only mode
// Cfile: moderead can be changed to cfile: modewrite (write only ),
// Cfile: modereadwrite (read/write), cfile: modecreate (new)
Example:
{
Cfile file;
File. Open ("C:/Hello. txt", cfile: modecreate | cfile: modewrite );
.
.
.
}
[3] Moving file pointers
File. Seek (100, cfile: Begin); // move down 100 bytes from the beginning of the file header
File. Seek (-50, cfile: End); // move up to 50 bytes from the end of the file
File. Seek (-30, cfile: Current); // move up 30 bytes from the current position
File. seektobegin (); // move to the file header
File. seektoend (); // move to the end of the file
[4] Reading and Writing files
Read files:
Char buffer [1000];
File. Read (buffer, 1000 );
Write File:
Cstring string ("self-improvement ");
File. Write (string, 8 );
[5] Close a file
File. Close ();