File Operations in Visual C ++ Programming

Source: Internet
Author: User
Various file operations are very common in program design. If you know all these operations well, you can find the best solution based on the actual situation, this allows you to write efficient code in a short period of time. This article provides a comprehensive introduction to file operations in Visual C ++, and analyzes in detail some difficult problems that are 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. In MFC, there is a class "cfilefind" dedicated for file search, 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-type parameter is used to specify whether to open or save the object. If it is true, a file opening dialog box is constructed, if this parameter is set to false, a file storage 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 allocating a piece of memory for the "m_ofn.lpstrfile" of the "cfiledialog" object to store all the file path names returned by the multiple-choice operation, if no allocation is made or the memory allocated 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_over
Writeprompt | 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 the "cfile" class. 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. Here we recommend the use of carchive, which is simple and powerful. First, we should declare an object with "cfile", and then declare a "carchive" object with the object pointer as a parameter, so that we can easily store various complex data types. For the usage method, 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 <strtemp;
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 Objects of the" cobject "derived class, readobject () and writeobject () are used for access (). 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. Read
Class ();
// Use the caboutdlg class
Cobject * pobject = mrunclass-> Createobject ();
(Cdialog *) pobject)-> domodal ();

Although these operations can be performed in the documents/visual structure provided by VC, they are not easy to understand, use, and manage. If the file operation to be performed is only a simple string for reading and writing the entire row, 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. It is often seen that there are a large number of extensions under the "C:/Windows/Temp" directory. TMP files. These are temporary files created during 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.

 

Related Article

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.