MFC file operations (cfile)

Source: Internet
Author: User

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

Note: (API) findfirstfile, findnextfile

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. Use cfiledialog to declare

The first bool parameter is used to specify whether to open or save a file. If it is set to true, a file open dialog box is created. If it is set to false, A File Save 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. Pay attention to this

The m_ofn.lpstrfile of the cfiledialog object allocates a piece of memory 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 occur.

Failed. 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 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. Carchive is recommended, which is simple and powerful. Use

Cfile declares an object, and then uses the pointer of this object as a parameter to declare a carchive object, which can easily store various complex data types. For how to use it, 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 (). Use

Carchive readclass () and writeclass () can also 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 ();

If the file to be operated 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. 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. Its first Parameter

The second parameter is the prefix of the temporary file name, and the fourth parameter is used to obtain the created temporary file name. After obtaining the temporary file name, you can use

It is used to create and operate files, 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. File-related functions in the SDK are commonly used: copyfile (), createdirectory (), deletefile ()

And movefile (). Their usage is simple. For details, refer to msdn.

Determine whether a file exists
Access (filename, mode );

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

 

**************************************** **************************************** *******



The cstdiofile class declaration is saved in the afx. h header file.



The cstdiofile class inherits from the cfile class. The cstdiofile object represents a streaming file of C Runtime opened by the runtime function fopen. Streaming files are buffered and can be opened in text (default) or binary mode.



The cstdiofile class does not support the duplicate, lockrange, and unlockrange functions in the cfile class. If you use the function, you will get an error of the cnotsupportedexception class.



By default, the cstringfile class operates files in text mode. The cfile class operates files in binary mode by default.



The difference between the binary mode and the text mode is roughly described here.



Binary Mode: for the end of a line, we must enter "/R/N" to indicate the effect of line breaks.



Text mode: "/R" The carriage return function is automatically completed. You only need to write "/N. Therefore, when we use the text mode again, when we read files from the external, "/R/N" will be translated into "/N". When writing files, we only need to provide "/N" for line breaks, and "/R/N" will be written to the file.



M_pstream member variable:



The pointer to open the file.



 



Constructor:



Cstdiofile ();



Cstdiofile (File * popenstream );



Cstdiofile (lpctstr lpfilename, uint nopenflags );



Throw (cfileexception );



File * popenstream: refers to the file pointer returned after the C-run function fopen is called.



Lptstr lpfilename: indicates the opened file (absolute address or relative address)



Uint nopenflags: indicates how to open a file described in the cfile class.



 



Virtual lptstr readstring (lptstr lpsz, uint Nmax );



Throw (cfileexception );



If you use this function to read text files, if you encounter "/R/N", stop reading, remove "/R", and retain "/N ", add "/0" at the end of the string. The Nmax length contains the "/0" character,



The actual analysis is as follows:



If Nmax <= characters, read (nMax-1) characters + 0x00;



If Nmax = characters + 1, read Nmax characters + 0x00;



If Nmax> Number of characters, read Nmax characters + 0x0a ("/N") + 0x00;



If the file contains multiple rows, if the file is not read, not null is returned. If the file is read at the end of the file, null is returned.



 



Bool readstring (cstring & rstring );



Throw (cfileexception );



When a line of text is read to rstring, the carriage return or line break will stop reading. The carriage return and line break will not be read to rstring, and "0x00" will not be added to the end ".



If the object contains multiple rows, true is returned when the object is not read. if the object is read at the end of the object, false is returned.



 



Virtual void writestring (lptstr lpsz );



Throw (cfileexception );



Write Data in the buffer to the file associated with the cstdiofile object. Data of the cstring type cannot be written. The ending "/0" is not written to the file, all linefeeds in the lpsz buffer are replaced by carriage return, that is, "/N" is converted to "/R/N ".

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.