Cfile
// Create/open a file
Cfile file;
File. Open (_ T ("test.txt"), cfile: modecreate | cfile: modenotruncate | cfile: modereadwrite );
The file opening mode can be used in combination and separated by "|". The following are commonly used:
Cfile: modecreate: open the file in the new mode. If the file does not exist, create it. If the file already exists, set the file length to zero, that is, clear the original file content.
Cfile: modenotruncate: it is opened in append mode. If the file exists, the file length is not set to zero. If the file does not exist, an exception is thrown. Generally used with cfile: modecreate. If the file does not exist, create a new file. If the file exists, append the file.
Cfile: modereadwrite: open a file in read/write mode.
Cfile: moderead: read-only.
Cfile: modewrite: Write-only.
// Write data
Cstring strvalue = "Hello world! ";
File. Write (strvalue, strvalue. getlength ());
// Append data
File. seektoend (); // move the pointer to the end of the file for appending
File. Write (strvalue, strvalue. getlength ());
// Close the file
File. Close ();
Cstdiofile
Cstdiofile is a cfile derived class that performs stream operations on files. It is useful for reading and writing text files and can be read and written by row.
// Write data
Cstring strvalue = "Hello world! ";
File. writestring (strvalue );
// Read data
Cstring strread;
File. readstring (strread );
When multiple lines of data exist in the file and need to be read row by row, the bool cstdiofile: readstring (cstring & rstring) function can be used. When "\ n" is encountered, the read is truncated. If the file has not been read, returns true; otherwise, returns false.
// Read the file content row by row and store it in strread
While (file. readstring (strread ))
{
...;
}
Various file operations are performed in Program It is very common in design. If you can know all of its operations, you can find the best solution based on the actual situation, so as to write efficient Code Therefore, it is very important to be familiar with 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 all the file pathnames returned by the multiple-choice operation. If no allocation or allocation of 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 establish and operateCompositionParts, such:
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 ();