C++

The mfc file manipulates the method of creating a file for the CFile class


mfc file action class CFile

Several constructors of the CFile class

CFile();// A constructor with no arguments.
CFile(int hFile);// Constructor with a file handle argument.
CFile(
LPCTSTR lpszFileName,// The path to the file to open
UINT nOpenFlage // Sharing and access mode when opening a file
);// Constructor with file path and open mode

In addition to opening the file with the constructor, you can open it with the member function Open of the CFile class

The OPen function prototype

virtual BOOL Open(
LPCTSTR lpszFilename,// The path to open the file can be either absolute or relative.
UINT nOpenFlags, // Sharing and access mode when opening a file.
CFileException *pError=NULL// Open the exception capture variable for the file
 ) ;

The arguments to CFile constructor and CFile member function Open can be any combination of the following (using a bit or | combination) :

CFile::modeCreate新建文件,如果文件已存在,则清空文件长度。
CFile::modeNotruncate与modeCreate组合使用。如果创建的文件已经存在,则打开已存在的文件,不存在则新建文件。
CFile::modeRead以只读方式打开文件。
CFile::modeWrite以只写方式打开文件。
CFile::modeNoInherit阻止文件从子进程中继承。
CFile::shareDenyNone共享读写的打开文件。
CFile::shareDenyRead排它读权限打开文件。
CFile::shareDenyWrite排它写权限打开文件。
CFile::shareExclusive排它模式打开文件。
CFile::typeText文本模式打开文件。
CFile::typeBinary2进制以写模式打开该文件。

Create the file and open the example:

void CMFCApplication42Dlg::OnBnClickedButton1()
{
  // TODO:  Add control notification handler code here
  CString filename = _T("C:\\Users\\Administrator\\Desktop\\test.txt"); // Define filename
  TRY // Exception handling
  {
    CFile f(filename, CFile::modeCreate | CFile::modeWrite);
  }
  CATCH (CFileException, e)// Abnormal trigger
  {
    #ifdef _DEBUG // If it's in debug mode
    afxDump << " Failed to open file " << e->m_cause << "\n";
    #endif

  }
  END_CATCH
}

conclusion

Above is the site to introduce mfc file operation CFile class to create the file method, I hope to help you, if you have any questions welcome to leave a message, this site will reply you in time!