CFile操作详解

上传人:泽*** 文档编号:67396773 上传时间:2022-03-31 格式:DOC 页数:11 大小:131KB
返回 下载 相关 举报
CFile操作详解_第1页
第1页 / 共11页
CFile操作详解_第2页
第2页 / 共11页
CFile操作详解_第3页
第3页 / 共11页
点击查看更多>>
资源描述
CFile 操作详解详解 ,CFile各种关于文件的操作在程序设计中是十分常见,如果能对其各种操作都了如指掌,就可以根据实际情况找到最佳的解决方案,从而在较短的时间内编写出高效的代码,因而熟练的掌握文件操作是十分重要的。本文将对 VisualC+ 中有关文件操作进行全面的介绍,并对在文件操作中经常遇到的一些疑难问题进行详细的分析。1文件的查找当对一个文件操作时,如果不知道该文件是否存在,就要首先进行查找。MFC中有一个专门用来进行文件查找的类CFileFind,使用它可以方便快捷地进行文件的查找。下面这段代码演示了这个类的最基本使用方法。CString strFileTitle;CFileFind finder;BOOL bWorking = finder.FindFile(C:windowssysbkup*.cab);while(bWorking)bWorking=finder.FindNextFile();strFileTitle=finder.GetFileTitle();2文件的打开/ 保存对话框让用户选择文件进行打开和存储操作时,就要用到文件打开/ 保存对话框。MFC的类CFileDialog用于实现这种功能。使用CFileDialog声明一个对象时,第一个BOOL型参数用于指定文件的打开或保存,当为TRUE时将构造一个文件打开对话框,为FALSE时构造一个文件保存对话框。在构造CFileDialog对象时,如果在参数中指定了OFN_ALLOWMULTISELECT风格,则在此对话框中可以进行多选操作。此时要重点注意为此CFileDialog对象的 m_ofn.lpstrFile分配一块内存,用于存储多选操作所返回的所有文件路径名,如果不进行分配或分配的内存过小就会导致操作失败。下面这段程序演示了文件打开对话框的使用方法。CFileDialog mFileDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,All Files (*.*)|*.*|,AfxGetMainWnd();CString str( ,10000);str.ReleaseBuffer();POSITION mPos=mFileDlg.GetStartPosition();CString pathName( ,128);CFileStatus status;while(mPos!=NULL)pathName=mFileDlg.GetNextPathName(mPos);CFile:GetStatus( pathName, status );3文件的读写文件的读写非常重要,下面将重点进行介绍。文件读写的最普通的方法是直接使用CFile 进行,如文件的读写可以使用下面的方法:/ 对文件进行读操作char sRead2;CFile mFile(_T(user.txt),CFile:modeRead);if(mFile.GetLength()2)return;mFile.Read(sRead,2);mFile.Close();/ 对文件进行写操作CFile mFile(_T(user.txt ), CFile:modeWrite|CFile:modeCreate);mFile.Write(sRead,2);mFile.Flush();mFile.Close();虽然这种方法最为基本,但是它的使用繁琐,而且功能非常简单。我向你推荐的是使用CArchive ,它的使用方法简单且功能十分强大。首先还是用CFile 声明一个对象,然后用这个对象的指针做参数声明一个 CArchive 对象,你就可以非常方便地存储各种复杂的数据类型了。它的使用方法见下例。/ 对文件进行写操作CString strTemp;CFile mFile;mFile.Open(d:ddtry.TRY,CFile:modeCreate|CFile:modeNoTruncate|CFile:modeWrite);CArchive ar(&mFile,CArchive:store);arstrTemp;ar.Close();mFile.Close();CArchive的 操作符用于简单数据类型的读写,对于CObject派生类的对象的存取要使用ReadObject()和 WriteObject()。使用CArchive的 ReadClass()和 WriteClass()还可以进行类的读写,如:/ 存储 CAboutDlg 类ar.WriteClass(RUNTIME_CLASS(CAboutDlg);/ 读取 CAboutDlg 类CRuntimeClass* mRunClass=ar.ReadClass();/ 使用 CAboutDlg 类CObject* pObject=mRunClass-CreateObject();(CDialog* )pObject)-DoModal();虽然 VC 提供的文档 / 视结构中的文档也可进行这些操作,但是不容易理解、使用和管理,因此虽然很多 VC入门的书上花费大量篇幅讲述文档/ 视结构,但我建议你最好不要使用它的文档。关于如何进行文档/ 视的分离有很多书介绍,包括非常著名的Visual C+技术内幕。如果你要进行的文件操作只是简单的读写整行的字符串,我建议你使用CStdioFile,用它来进行此类操作非常方便,如下例。CStdioFile mFile;CFileException mExcept;mFile.Open( d:tempaa.bat, CFile:modeWrite, &mExcept);CString string=I am a string.;mFile.WriteString(string);mFile.Close();4临时文件的使用正规软件经常用到临时文件,你经常可以会看到C:WindowsTemp 目录下有大量的扩展名为tmp 的文件,这些就是程序运行是建立的临时文件。临时文件的使用方法基本与常规文件一样,只是文件名应该调用函数 GetTempFileName() 获得。它的第一个参数是建立此临时文件的路径,第二个参数是建立临时文件名的前缀,第四个参数用于得到建立的临时文件名。得到此临时文件名以后,你就可以用它来建立并操作文件了,如: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文件的复制、删除等MFC中没有提供直接进行这些操作的功能,因而要使用SDK。SDK中的文件相关函数常用的有CopyFile()、CreateDirectory()、 DeleteFile()、MoveFile()。它们的用法很简单,可参考MSDN。1, 判断文件是否存在access(filename,mode);2, 对于不同用途又不同的文件操作, 其中 API 函数 CreateFile()也是比较有用处理方式, 对于巨型文件很合适的其他的楼上的大都说了, 不重复了 .1 显示对话框,取得文件名CString FilePathName;CFileDialog dlg(TRUE);/TRUE为 OPEN对话框, FALSE为 S*E AS 对话框if (dlg.DoModal() = IDOK)FilePathName=dlg.GetPathName();相关信息: CFileDialog用于取文件名的几个成员函数:假如选择的文件是C:WINDOWSTEST.EXE则 (1)GetPathName();取文件名全称,包括完整路径。取回C:WINDOWSTEST.EXE(2)GetFileTitle();取文件全名:TEST.EXE(3)GetFileName();取回TEST(4)GetFileExt();取扩展名EXE2 打开文件CFile file(C:HELLO.TXT,CFile:modeRead);/只读方式打开/CFile:modeRead可改为CFile:modeWrite(只写 ),/CFile:modeReadWrite(读写 ),CFile:modeCreate(新建 )例子:CFile file;file.Open(C:HELLO.TXT,CFile:modeCreate|Cfile:modeWrite);.3 移动文件指针file.Seek(100,CFile:begin);/从文件头开始往下移动100 字节file.Seek(-50,CFile:end);/从文件末尾往上移动 50字节file.Seek(-30,CFile:current);/从当前位置往上移动30字节file.SeekToBegin();/移到文件头file.SeekToEnd();/移到文件尾4 读写文件读文件:char buffer1000;file.Read(buffer,1000);写文件:CString string(自强不息 );file.Write(string,8);5 关闭文件file.Close();参数内容 :第一个参数为路径+文件名 , 最后一个为错误出现的结构.现在解释下第二个参数CFile:modeCreateDirects the constructor to create a new file. If the file existsalready, it is truncated to 0 length.指定构造器创建一个新的文件, 如果文件已经存在, 则内容截0.CFile:modeNoTruncateCombine this value with modeCreate. If thefile being createdalready exists, it is not truncated to 0 length.Thus the file is guaranteed to open, either as a newly created file oras an existing file. This might be useful, for example, when opening asettings file that may or may not exist already. This option applies toCStdioFile as well.modeNoTruncate假如你不用这个参数的话,用modeCreate 模式创建和打开一个文件,假如这个文件已经存在,则会清空这个已经存在的文件,加上modeNoTruncate 的话,就不会清空这个文件了CFile:modeReadOpens the file for reading only.只是以读取方式打开CFile:modeReadWriteOpens the file for reading and writing.读与写同时CFile:modeWriteOpens the file for writing only.只写CFile:modeNoInheritPrevents the file from being inherited by child processes.阻止这个文件被子进程继承CFile:shareDenyNoneOpens the file without denying otherprocesses read or write accessto the file. Create fails if the filehas been opened in compatibility mode by any otherprocess.打开这个文件同时允许其它进程读写这个文件。如果文件被其它进程以incompatibility模式打开,这是create操作会失败。CFile:shareDenyReadOpens the file and denies other processesread access to the file.Create fails if the file has been opened incompatibility mode or for read access by anyother process.打开文件拒绝其它任何进程读这个文件。如果文件被其它进程用compatibility模式或者是读方式打开,create操作失败。CFile:shareDenyWriteOpens the file and denies other processeswrite access to the file.Create fails if the file has been opened incompatibility mode or for write access by anyother process.打开文件拒绝其它任何进程写这个文件。如果文件被其它进程用compatibility模式或者是写方式打开,create操作失败。CFile:shareExclusiveOpens the file with exclusive mode, denyingother processes bothread and write access to the file. Constructionfails if the file has been opened in any other mode for read or writeaccess, even by the current process.以独占方式打开这个文件,不允许其它进程读写这个文件。CFile:shareCompat This flag is not available in 32 bit MFC. This flag maps to CFile:shareExclusive when used in CFile:Open.这个标志在32 位的MFC中无效。CFile:typeTextSets text mode with special processing for carriage return linefeedpairs (used in derived classes only).CFile:typeText设置成对回车换行对有特殊处理的文本模式(仅用在派生类中)CFile:typeBinary设置二进制模式(仅用在派生类中)CStdioFile:ReadStringvirtual LPTSTR ReadString( LPTSTR lpsz, UINT nMax ); throw( CFileException );BOOL ReadString(CString& rString);throw( CFileException );Return Value直接通过 ODBC读、写 Excel 表格文件ODBC,Excel ,表格 ,文件下面的代码是不是要在mfc 里搞的想要通过ODBC直接读、写Excel 表格文件,首先,应确保ODBC中已安装有Excel 表格文件的驱动MICROSOFT EXCEL DRIVER (*.XLS)。然后,可根据下面步骤进行:1.在 StdAfx.h文件中加入:include include 2.通过 ODBC直接创建Excel 文件 ( 暂定文件名: Demo.xls)/ 创建并写入Excel 文件void CRWExcel:WriteToExcel()CDatabase database;CString sDriver = MICROSOFT EXCEL DRIVER (*.XLS); / ExcelCString sExcelFile = c:demo.xls;/要建立的Excel 文件CString sSql;TRY/ 创建进行存取的字符串sSql.Format(DRIVER=%s;DSN=;FIRSTROWHASNAMES=1;READONLY=FALSE;CREATE_DB=%s;DBQ=%s,sDriver, sExcelFile, sExcelFile);/ 创建数据库 ( 既 Excel 表格文件 )if( database.OpenEx(sSql,CDatabase:noOdbcDialog) )/ 创建表结构 ( 姓名、年龄 )sSql = CREATE TABLE demo (Name TEXT,Age NUMBER);database.ExecuteSQL(sSql);/ 插入数值sSql = INSERT INTO demo (Name,Age) VALUES (徐景周 ,26);database.ExecuteSQL(sSql);sSql = INSERT INTO demo (Name,Age) VALUES (徐志慧 ,22);database.ExecuteSQL(sSql);sSql = INSERT INTO demo (Name,Age) VALUES (郭徽 ,27);database.ExecuteSQL(sSql);/ 关闭数据库database.Close();CATCH_ALL(e)TRACE1(Excel 驱动没有安装 : %s,sDriver);END_CATCH_ALL;3.通过 ODBC直接读取Excel 文件 ( 暂定文件名: Demo.xls)/ 读取 Excel 文件void CRWExcel:ReadFromExcel()CDatabase database;CString sSql;CString sItem1, sItem2;CString sDriver;CString sDsn;CString sFile = Demo.xls;/将被读取的Excel 文件名/ 检索是否安装有 Excel 驱动 Microsoft Excel Driver (*.xls) sDriver = GetExcelDriver();if (sDriver.IsEmpty()/ 没有发现 Excel 驱动AfxMessageBox( 没有安装Excel 驱动 !;return;/ 创建进行存取的字符串sDsn.Format(ODBC;DRIVER=%s;DSN=;DBQ=%s, sDriver, sFile);TRY/ 打开数据库 ( 既 Excel 文件 ) database.Open(NULL, false, false, sDsn);CRecordset recset(&database);/ 设置读取的查询语句 . sSql = SELECT Name, Age FROM demo ORDER BY Name ;/ 执行查询语句recset.Open(CRecordset:forwardOnly, sSql, CRecordset:readOnly);/ 获取查询结果while (!recset.IsEOF()/ 读取 Excel 内部数值recset.GetFieldValue(Name , sItem1);recset.GetFieldValue(Age, sItem2);/ 移到下一行recset.MoveNext();/ 关闭数据库database.Close();CATCH(CDBException, e)/ 数据库操作产生异常时 .AfxMessageBox( 数据库错误 : + e-m_strError);END_CATCH;/ 获取 ODBC中 Excel 驱动CString CRWExcel:GetExcelDriver()char szBuf2001;WORD cbBufMax = 2000;WORD cbBufOut;char *pszBuf = szBuf;CString sDriver;/获取已安装驱动的名称( 涵数在 odbcinst.h里)if (!SQLGetInstalledDrivers(szBuf, cbBufMax, &cbBufOut)return ;/检索已安装的驱动是否有Excel.doif (strstr(pszBuf, Excel!= 0)/发现!sDriver = CString(pszBuf);break;pszBuf = strchr(pszBuf, 0) + 1;while (pszBuf1 != 0);return sDriver;感谢您的阅读,祝您生活愉快。
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 管理文书 > 各类标准


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!