VC + + file operation (i)---cfilefind,cfiledialog,cfile,carchive,cstdiofile

Source: Internet
Author: User

A variety of files on the operation of the program is very common, if it can be a variety of operations are well-known, you can find the best solution according to the actual situation, so that in a short period of time to write efficient code, so skilled master file operation is very important. This article provides a comprehensive overview of the file operations in Visual C + + and provides a detailed analysis of some of the difficult issues that are frequently encountered in file operations.

VC + + file operation (i)

***************************************************************************
XXXXXXXXXX First, VC related file operations, reference 1
***************************************************************************

1. File Lookup---cfilefind
If you do not know if the file exists, you will need to find it first when you operate on a file. MFC has a class CFileFind , which is specifically used for file lookups. It can be used to find files quickly and easily. The following code demonstrates the most basic use of this class.  

123 BOOL bworking = Finder. FindFile ("c:\\windows\\sysbkup\\*.cab"4 while  5  6 bworking= 7 strfiletitle= 8}    

 2. Opening/saving of dialog file---CFileDialog
The File Open/Save dialog box is used when the user selects a file for opening and storing operations. MFC's class CFileDialog is used to implement this functionality. When you use CFileDialog to declare an object, the first bool parameter is used to specify the opening or saving of the file, and when True, constructs a File Open dialog box, False when a File Save dialog box is constructed.
When you construct a CFileDialog object, you can make multiple selections in this dialog box if you specify a ofn_allowmultiselect style in the parameters. It is important to note that the m_ofn.lpstrfile of this CFileDialog object is allocated a piece of memory to store all the file pathname returned by the multi-select operation, which causes the operation to fail if it is not allocated or the allocated memory is too small. The following procedure demonstrates how to use the File Open dialog box.

1 CFileDialog Mfiledlg (True,null,null,2ofn_hidereadonly| Ofn_overwriteprompt|Ofn_allowmultiselect,3     "All Files (*. *) |*.*| |", AfxGetMainWnd ()); 4CString Str (" ",10000); 5Mfiledlg.m_ofn.lpstrfile=str. GetBuffer (10000); 6 Str. ReleaseBuffer (); 7POSITION mpos=mfiledlg.getstartposition ();8CString PathName (" ", -); 9 cfilestatus status;Ten      while(mpos!=NULL) One { APathname=Mfiledlg.getnextpathname (mPos); - CFile::GetStatus (pathName, status); -}

3. Read and write Files---cfile,carchive,cstdiofile
It is important to read and write files, which are highlighted below. The most common way to read and write files is to use CFile directly, such as file read and write can use the following method:

1 //Read the file2     Charsread[2]; 3CFile Mfile (_t ("User.txt"), cfile::moderead); 4     if(Mfile.getlength () <2) 5     return; 6Mfile.read (Sread,2); 7 Mfile.close ();
8    //write to a file9CFile Mfile (_t ("User.txt"), cfile::modewrite|cfile::modecreate); TenMfile.write (Sread,2); One Mfile.flush (); AMfile.close ();

Although this method is the most basic, it is cumbersome to use, and the function is very simple. What I recommend to you is the use of CArchive, which is simple to use and very powerful. You can easily store a variety of complex data types by declaring an object with CFile and then declaring a CArchive object with a pointer to that object. The use of this method is shown in the following example.

1     //write to a file2 CString strtemp;3 CFile Mfile;4Mfile.open ("D:\\dd\\try. TRY", cfile::modecreate| cfile::modenotruncate|cfile::modewrite); 5CArchive ar (&Mfile,carchive::store); 6ar<<ar. Close (); 7 Mfile.close ();
8    //Read the file9 CFile Mfile;Ten    if(Mfile.open ("D:\\dd\\try. TRY", cfile::moderead) = =0) One    return; ACArchive ar (&mfile,carchive::load); -Ar>>strtemp; - ar. Close (); theMfile.close ();

  

     carchive << and >> operators are used for reading and writing simple data types, For access to objects of the CObject derived class, use ReadObject () and WriteObject (). Using CArchive's ReadClass () and WriteClass () can also be used to read and write classes, such as:  

1 //  2 3//4 cruntimeclass* mrunclass= 5  //6 cobject* pobject=mrunclass->7        

  

Although the documentation/visual structure provided by the VC is also available for these operations, it is not easy to understand, use, and manage, so although many of the VC introductory books spend a lot of time talking about the document/view structure, I recommend that you do not use its documentation. There are a lot of books on how to separate documents/views, including the very famous Visual C + + technology Insider.

If the file you want to do is simply read and write the entire line of string, I suggest you use CStdioFile, it is very convenient for this kind of operation, the following example.

123"d:\\temp\\aa.bat", Cfile::modewrite, &4string="I am a string". "  5 mfile.writestring (string6 mfile.close ();

4. Use of temporary Files---gettempfilename ()
Regular software often use temporary files, you can often see the C:\Windows\Temp directory has a large number of files with the extension TMP, these are the temporary files that the program runs is established. Temporary files are used in the same way as regular files, except that the file name should be obtained by calling function GetTempFileName (). The first parameter is the path to this temporary file, the second parameter is the prefix for creating the temporary filename, and the fourth parameter is used to get the temporary filename created. After you get this temporary file name, you can use it to create and manipulate files, such as:

1     CharSztemppath[_max_path],sztempfile[_max_path];2 GetTempPath (_max_path, sztemppath);3GetTempFileName (sztemppath,_t ("My_"),0, Sztempfile); 4CFile M_tempfile (sztempfile,cfile:: modecreate|CFile:: Modewrite); 5     CharM_char='a'; 6M_tempfile.write (&m_char,2); 7M_tempfile.close ();

5. copying, deleting, etc. of files
MFC does not provide the functionality to do these things directly, so use the SDK. FILE-related functions in the SDK are commonly used with copyfile (), CreateDirectory (), DeleteFile (), MoveFile (). They are very simple to use and can be consulted on MSDN.

*************************************************************************
Xxxxxxxxxx Second, VC related file operations, reference 2
*************************************************************************
How to perform file operations

[1] Show dialog box, get file name

CString Filepathname;
CFileDialog dlg (TRUE);///true is the Open dialog box, False is the Save As dialog box
if (dlg. DoModal () = = IDOK)
Filepathname=dlg. GetPathName ();

Related information: CFileDialog several member functions for fetching file names:

If the selected file is C:\WINDOWS\TEST. EXE, you
(1) GetPathName (); Take the full file name, including the complete path. Retrieve the C:\WINDOWS\TEST. Exe
(2) GetFileTitle (); Take file full name: TEST.EXE
(3) GetFileName (); Retrieve test
(4) Getfileext (); Take extension exe

[2] Open File
CFile file ("C:\HELLO. TXT ", cfile::moderead);//read-only mode open
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 the file pointer
File. Seek (100,cfile::begin);///100 bytes from the beginning of the file header
File. Seek ( -50,cfile::end);///50 bytes from the end of the file
File. Seek ( -30,cfile::current);///30 bytes from the current position
File. Seektobegin ();///move to file header
File. Seektoend ();///move to end of file

[4] Read and write files
Read the file:
Char buffer[1000];
File. Read (buffer,1000);
Write file:
CString string ("self-reliance");
File. Write (string,8);

[5] Closing files
File. Close ();

***********************************************************************
Xxxxxxxxxx Third, VC related file operations, reference 3
***********************************************************************

VC + + in append to the text file to write data---cstdiofile

It is easy to append data to a text file in VB and ASP, as long as you set a parameter to ForAppending.

1 Sub opentextfiletest2 3Const ForReading =1, ForWriting =2, ForAppending =84 5 Dim FSO, F6 7Set FSO = CreateObject ("Scripting.FileSystemObject")8 9Set f = fso. OpenTextFile ("C:\testfile.txt", ForWriting, True)Ten  OneF.write"Hello world!" A  - F.close -  theEnd Sub

in the C language, append data is also relatively simple, as if the set of a + parameter can be. Today, I want to use MFC in the CStdioFile class for file operations, read and write, and so on.

But, look, there seems to be no easy way, so on the internet to see the wording:

1 cstdiofile file (strfile,cfile::modecreate| cfile::modenotruncate| cfile::modewrite); 2 3 file. WriteString (strtmp); 4 5 file. Close;

the meaning of modenotruncate is not to intercept. However, the test of this code, and did not work, do not know what the reason.

So, before WriteString writes the string, it is possible to add a pointer to the code at the end of the file.

1 CString strtmp="hehe\r\n"; 2  3 cstdiofile file (strfile,cfile::modecreate| cfile::modenotruncate| cfile::modewrite); 4 5 file. Seektoend (); // Locate the end of the file first 6 7 file. WriteString (strtmp); 8 9 file. Close;

Organized from: http://www.cnblogs.com/lidabo/p/3470085.html

VC + + file operation (i)---cfilefind,cfiledialog,cfile,carchive,cstdiofile

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.