CFile and CStdioFile file reading and writing methods

  • 2020-04-02 01:36:02
  • OfStack

CFile
// create/open the file
CFile file;
Test. TXT file. Open (_T (" "), CFile: : modeCreate | CFile: : modeNoTruncate | CFile: : modeReadWrite);

File open mode can be used in combination, separated by "|", there are several commonly used:
CFile: : modeCreate: Open in new mode, if the file does not exist, new; If the file already exists, set the length of the file to zero to clear the original contents of the file.

CFile: : modeNoTruncate: Open as an append, if the file exists, open and do not set the file length to zero, if the file does not exist, an exception is thrown. This is generally used with CFile::modeCreate, which creates a new file if the file does not exist. Append operations as they exist.
CFile: : modeReadWrite: Open the file in read-write mode.
CFile: : modeRead: Read-only.
CFile: : modeWrite: Just write.

// write data
CString strValue = "Hello World!" ;
File. The Write (strValue, strValue GetLength ());

// append data
File. SeekToEnd (); // move the pointer to the end of the file to append
File. The Write (strValue, strValue GetLength ());

// close the file
File. The Close ();

CStdioFile
CStdioFile is a derived class of CFile that streams files, is useful for reading and writing text files, and can be read and written by line.

// write data
CString strValue = "Hello World!" ;
File. WriteString (strValue);

// read data
Cstrings strRead;
File. The ReadString (strRead);

The function BOOL CStdioFile::ReadString(CString& rString) can be used when there are more than one line of data in a file and it needs to be read line by line. The function BOOL CStdioFile::ReadString(CString& rString) is truncated when "/n "is encountered.

// reads the contents of the file line by line and stores it in strRead
While (file. ReadString (strRead))
{
  . ;
}

Various operations on the file is very common in the program design, if you can understand its various operations, you can find the best solution according to the actual situation, so in a short time to write efficient code, so it is very important to master the file operation. This article will be Visual C++ in the file operation for a comprehensive introduction, and often encountered in the file operation of some difficult problems for detailed analysis.

1. Search of files
When operating on a file, if you do not know if the file exists, you first look it up. There is a special class CFileFind in MFC for file lookup, which can be easily and quickly used for file lookup. The following code demonstrates the most basic use 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 open/save dialog box
The file open/save dialog box is used to let the user select a file to open and store. MFC's CFileDialog class is used to implement this functionality. When an object is declared with CFileDialog, the first BOOL parameter is used to specify the opening or saving of the file, a file opening dialog is constructed when TRUE, and a file saving dialog is constructed when FALSE.

When constructing a CFileDialog object, if the OFN_ALLOWMULTISELECT style is specified in the parameter, the multiselect operation can be performed in this dialog box. It is important to note that the m_ofn.lpstrfile of this CFileDialog object allocates a block of memory to store all the file pathnames returned by the multi-select operation. If the allocation is not made or too little memory is allocated, the operation will fail. The following procedure demonstrates the use of the file opening dialog.

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. File reading and writing
Reading and writing files is very important and will be highlighted below. The most common way to read and write a file is to use CFile directly.

// read the file
Char sRead [2].
CFile mFile (_T (" user. TXT "), CFile: : modeRead);
If (mFile GetLength () < 2)
The return;
MFile. Read (sRead, 2);
MFile. Close ();

// write to the 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, it is cumbersome to use and very simple in function. What I recommend to you is to use CArchive, which is simple to use and very powerful. First declare an object with a CFile, then declare a CArchive object with a pointer to that object as an argument, and you can easily store all kinds of complex data types. See the following example for how to use it.

// write to the file
Cstrings strTemp;
CFile mFile;
MFile. Open (" d: / / dd / / try. Try ", CFile: : modeCreate | CFile: : modeNoTruncate | CFile: : modeWrite);
CArchive ar (& mFile, CArchive: : store);
ar < < Ar. The Close ();
MFile. Close ();

// read the file
CFile mFile;
If (mFile. Open (" d: / / dd / / try. Try ", CFile: : modeRead) = = 0)
The return;
CArchive ar (& mFile, CArchive: : load).
ar > > StrTemp;
      Ar. The Close ();
MFile. Close ();

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

// store 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 documentation in the document/visual structure provided by VC can also do this, it is not easy to understand, use, and manage, so while many introductory VC books spend a lot of time on the document/visual structure, I recommend that you do not use its documentation. There are many books on how to do document/Visual separation, including the well-known Visual C++ technology insider.
If your file operation is simply to read and write an entire line of strings, I recommend that you use CStdioFile, which is very handy for this type of operation, as shown in the following example.


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, you will 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 is running to create. Temporary files are used in much the same way as regular files, except that the file name should be obtained by calling the function GetTempFileName(). The first parameter is the path to create the temporary file, the second parameter is the prefix to create the temporary file name, and the fourth parameter is used to get the created temporary file name. Once you have this temporary file name, you can use it to create and manipulate files, such as:

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, delete, etc
The ability to do this directly is not available in MFC, so use the SDK. File related functions in the SDK are CopyFile(), CreateDirectory(), DeleteFile(), and MoveFile(). Their usage is very simple, can refer to MSDN.

1. Determine whether the file exists
  Access (filename, mode);

2. The API function CreateFile() is also useful for different file operations for different purposes, and is suitable for giant files.

[1] display the dialog box and get the file name


CString FilePathName;
CFileDialog dlg(TRUE);///TRUE is the OPEN dialog box, FALSE is the S***E AS dialog box
if (dlg.DoModal() == IDOK)
    FilePathName=dlg.GetPathName();

Related information: Several member functions used by CFileDialog to fetch file names:
Suppose the file selected is C:/WINDOWS/ test.exe
the
(1) GetPathName (); Take the full name of the file name, including the full path. Retrieve the C: / WINDOWS/TEST. EXE
(2) GetFileTitle (); Take the full name of the file: test.exe
(3) the GetFileName (); Retrieve the TEST
(4) GetFileExt (); Take the extension EXE

[2] open the file
CFile file (" C: / HELLO. TXT ", CFile: : modeRead); // read-only mode open
//CFile::modeRead can be changed to CFile::modeWrite,
//CFile::modeReadWrite(read and write),CFile:: modecate (new)
Example:


{
CFile file;
file.Open("C:/HELLO.TXT",CFile::modeCreate|Cfile::modeWrite);
.
.
.
}

[3] move the file pointer
File. The Seek (100, CFile: : begin); /// move down 100 bytes from the file header
File. The Seek (- 50, CFile: : end); /// move up 50 bytes from the end of the file
File. The Seek (30, CFile: : current); /// move up 30 bytes from the current position
File. SeekToBegin (); /// move to file header
File. SeekToEnd (); /// move to the end of the file

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

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


Related articles: