CFile and CStdioFile file read and write use of the method detailed _c language

Source: Internet
Author: User
Tags throw exception

CFile
Create/Open File
CFile file;
File. Open (_t ("Test.txt"), cfile::modecreate| cfile::modenotruncate| Cfile::modereadwrite);

File open mode can be used in combination with the "|" Separated, commonly used in the following categories:
cfile::modecreate: Open in new mode, if the file does not exist, new, if the file already exists, the file length to zero, that is, clear the original contents of the file.

cfile::modenotruncate: Open in Append mode, if file exists, open and do not zero file length, throw exception if file does not exist. Typically used with Cfile::modecreate, a new file is created when the file is not present, and an append operation exists.
cfile::modereadwrite: Opens the 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 to append
File. Write (Strvalue,strvalue.getlength ());

Close File
File. Close ();

CStdioFile
CStdioFile is a derived class of CFile, which is useful for reading and writing text files, and for streaming files.

Write Data
CString strvalue = "Hello world!";
File. WriteString (strvalue);

Reading data
CString Strread;
File. ReadString (Strread);

When a file has multiple rows of data that needs to be read line by row, the available functions bool Cstdiofile::readstring (cstring& rstring), read truncation when "/n" is encountered, and return True if the file is not read, or false.

Read the contents of the file line by row and deposit Strread
while (file. ReadString (Strread))
{
...;
}

A variety of documents on the operation of the program is very common in the design, if you can understand all of its operations, you can find the best solution according to the actual situation, so in a relatively short period of time to write efficient code, so skilled master file operation is very important. This article will provide a comprehensive description of the file operations in Visual C + + and a detailed analysis of some of the difficult problems that are often encountered in file operations.

1. Search for files
When working on a file, if you do not know if the file exists, you must first find it. MFC has a special class CFileFind for file lookup, which makes it easy and quick to find files. The following code illustrates the most basic use of this class.

Copy Code code as follows:

CString Strfiletitle;
CFileFind Finder;
BOOL bworking = Finder. FindFile ("C://windows//sysbkup//*.cab");
while (bworking)
{
Bworking=finder. FindNextFile ();
Strfiletitle=finder. GetFileTitle ();
}

2. Open/Save dialog box for file
The File Open/Save dialog box is used when a user chooses a file to open and store operations. MFC's class CFileDialog is used to implement this functionality. When declaring an object using CFileDialog, the first bool parameter is used to specify that the file be opened or saved, and a File Open dialog box is constructed when True, and a File Save dialog box is constructed when false.

When you construct a CFileDialog object, if you specify a ofn_allowmultiselect style in the argument, you can do multiple selections in this dialog box. It is important to note that the m_ofn.lpstrfile of this CFileDialog object is allocated a piece of memory for storing all the file path names returned by the multiple-selection operation, which can cause the operation to fail if the memory is not allocated or allocated too little. The following program demonstrates how to use the File Open dialog box.
Copy Code code as follows:

CFileDialog Mfiledlg (True,null,null,
ofn_hidereadonly| Ofn_overwriteprompt| Ofn_allowmultiselect,
"All Files (*.*) |*.*| |", AfxGetMainWnd ());
CString Str ("", 10000);
Mfiledlg.m_ofn.lpstrfile=str. GetBuffer (10000);
Str. ReleaseBuffer ();
POSITION mpos=mfiledlg.getstartposition ();
CString pathName ("", 128);
CFileStatus status;
while (Mpos!=null)
{
Pathname=mfiledlg.getnextpathname (MPOs);
CFile::GetStatus (pathName, status);
}

3. Reading and writing of files
The reading and writing of files is very important, and the following are the highlights. The most common way to read and write files is to use CFile directly, such as reading and writing files using the following methods:

Read to a file
Char sread[2];
CFile Mfile (_t ("User.txt"), Cfile::moderead);
if (Mfile.getlength () <2)
Return
Mfile.read (sread,2);
Mfile.close ();

Write to a file
CFile Mfile (_t ("User.txt"), cfile::modewrite| Cfile::modecreate);
Mfile.write (sread,2);
Mfile.flush ();
Mfile.close ();

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

Write to a file
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 to a file
CFile Mfile;
if (Mfile.open ("D://dd//try. TRY ", Cfile::moderead) ==0)
Return
CArchive ar (&mfile,carchive::load);
ar>>strtemp;
Ar. Close ();
Mfile.close ();

CArchive's << and >> operators are used for reading and writing simple data types, and for accessing objects of CObject derived classes using ReadObject () and WriteObject (). The CArchive ReadClass () and WriteClass () can also be used to read and write classes, such as:

Storage CAboutDlg Class
Ar. WriteClass (Runtime_class (CAboutDlg));

Read CAboutDlg class
Cruntimeclass* Mrunclass=ar. ReadClass ();

Using the CAboutDlg class
cobject* Pobject=mrunclass->createobject ();
((cdialog*) pobject)->domodal ();

Although VC provides documents/visual structure of the documents can also do these operations, but not easy to understand, use and management, so although many VC introductory book to spend a lot of space on the document/visual structure, but I suggest you should not use its documentation. There are a number of books on how to document/view separation, including the very famous Visual C + + technology Insider.
If the file you are working on is simply reading and writing the entire line of strings, I recommend that you use CStdioFile, which is handy for this type of operation, as in the following example.

Copy Code code as follows:

CStdioFile Mfile;
CFileException mexcept;
Mfile.open ("D://temp//aa.bat", Cfile::modewrite, &mexcept);
CString string= "I am a string.";
Mfile.writestring (string);
Mfile.close ();

4. Use of temporary files
Regular software often uses temporary files, and you can often see a large number of files with the extension TMP in the C:/windows/temp directory, which is the temporary file that the program runs. The use of temporary files is basically the same as regular files, except that the filename should be obtained by calling the function GetTempFileName (). Its first parameter is the path to establish this temporary file, the second parameter is the prefix to establish the temporary file name, and the fourth parameter is used to get the temporary file name that was established. After you get this temporary file name, you can use it to create and manipulate files, such as:
Copy Code code as follows:

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. File replication, deletion, etc.
MFC does not provide the ability to perform these operations directly, and therefore uses the SDK. The file-related functions in the SDK are commonly used for copyfile (), CreateDirectory (), DeleteFile (), MoveFile (). They are simple to use and refer to MSDN.

1, to determine whether the file exists
Access (Filename,mode);

2, for different uses and different file operations, where the API function CreateFile () is also a more useful way to deal with the huge file is suitable for the other upstairs most of the said, do not repeat.

[1] Display dialog box, get filename

Copy Code code as follows:

CString Filepathname;
CFileDialog Dlg (TRUE);///true as Open dialog box, False s***e as dialog box
if (dlg. DoModal () = = Idok)
Filepathname=dlg. GetPathName ();

Related information:CFileDialog Several member functions used to take a filename:
If the selected file is C:/windows/test. Exe
The
(1) getpathname (); The full name of the filename, including the complete path. Retrieve the C:/windows/test. Exe
(2) GetFileTitle (); Full file name: TEST.EXE
(3) GetFileName () Fetch test
(4) Getfileext (), taking the 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 and write), Cfile::modecreate (new)
Example:

Copy Code code as follows:

{
CFile file;
File. Open ("C:/hello.") TXT ", cfile::modecreate| Cfile::modewrite);
.
.
.
}

[3] Moving the file pointer
File. Seek (100,cfile::begin);///move 100 bytes down from the file header
File. Seek ( -50,cfile::end);///move 50 bytes up from the end of the file
File. Seek ( -30,cfile::current);///move 30 bytes up 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-improvement");
File. Write (string,8);

[5] Close the file
File. Close ();

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.