vc中常用文件操作(转载)

来源:百度文库 编辑:神马文学网 时间:2024/04/27 13:44:56
各种关于文件的操作在程序设计中是十分常见,如果能对其各种操作都了如指掌,就可以根据实际情况找到最佳的解决方案,从而在较短的时间内编写出高效的代码,因而熟练的掌握文件操作是十分重要的。本文将对Visual C++中有关文件操作进行全面的介绍,并对在文件操作中经常遇到的一些疑难问题进行详细的分析。
1.文件的查找
当对一个文件操作时,如果不知道该文件是否存在,就要首先进行查找。MFC中有一个专门用来进行文件查找的类CFileFind,使用它可以方便快捷地进行文件的查找。下面这段代码演示了这个类的最基本使用方法。
CString strFileTitle;
CFileFind finder;
BOOL bWorking = finder.FindFile  ("C:\\windows\\sysbkup\\*.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);
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.文件的读写
文件的读写非常重要,下面将重点进行介绍。文件读写的最普通的方法是直接使用CFile进行,如文件的读写可以使用下面的方法:
//对文件进行读操作
char sRead[2];
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();
虽然这种方法最为基本,但是它的使用繁琐,而且功能非常简单
4.临时文件的使用
正规软件经常用到临时文件,你经常可以会看到C:\Windows\Temp目录下有大量的扩展名为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。
在我们写的程序当中,总有一些配置信息需要保存下来,以便完成程序的功能,最简单的办法就是将这些信息写入INI文件中,程序初始化时再读入.具体应用如下:
一.将信息写入.INI文件中.
1.所用的WINAPI函数原型为:
BOOL WritePrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpString,
LPCTSTR lpFileName
);
其中各参数的意义:
LPCTSTR lpAppName 是INI文件中的一个字段名.
LPCTSTR lpKeyName 是lpAppName下的一个键名,通俗讲就是变量名.
LPCTSTR lpString 是键值,也就是变量的值,不过必须为LPCTSTR型或CString型的.
LPCTSTR lpFileName 是完整的INI文件名.
2.具体使用方法:设现有一名学生,需把他的姓名和年龄写入 c:\stud\student.ini 文件中.
CString strName,strTemp;
int nAge;
strName="张三";
nAge=12;
::WritePrivateProfileString("StudentInfo","Name",strName,"c:\\stud\\student.ini");
此时c:\stud\student.ini文件中的内容如下:
[StudentInfo]
Name=张三
3.要将学生的年龄保存下来,只需将整型的值变为字符型即可:
strTemp.Format("%d",nAge);
::WritePrivateProfileString("StudentInfo","Age",strTemp,"c:\\stud\\student.ini");
二.将信息从INI文件中读入程序中的变量.
1.所用的WINAPI函数原型为:
DWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault,
LPTSTR lpReturnedString,
DWORD nSize,
LPCTSTR lpFileName
);
其中各参数的意义:
前二个参数与 WritePrivateProfileString中的意义一样.
lpDefault : 如果INI文件中没有前两个参数指定的字段名或键名,则将此值赋给变量.
lpReturnedString : 接收INI文件中的值的CString对象,即目的缓存器.
nSize : 目的缓存器的大小.
lpFileName : 是完整的INI文件名.
2.具体使用方法:现要将上一步中写入的学生的信息读入程序中.
CString strStudName;
int nStudAge;
GetPrivateProfileString("StudentInfo","Name","默认姓名",strStudName.GetBuffer(MAX_PATH),MAX_PATH,"c:\\stud\\student.ini");
执行后 strStudName 的值为:"张三",若前两个参数有误,其值为:"默认姓名".
3.读入整型值要用另一个WINAPI函数:
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
INT nDefault,
LPCTSTR lpFileName
);
这里的参数意义与上相同.使用方法如下:
nStudAge=GetPrivateProfileInt("StudentInfo","Age",10,"c:\\stud\\student.ini");
三.循环写入多个值,设现有一程序,要将最近使用的几个文件名保存下来,具体程序如下:
1.写入:
CString strTemp,strTempA;
int i;
int nCount=6;
file://共有6个文件名需要保存
for(i=0;i {strTemp.Format("%d",i);
strTempA=文件名;
file://文件名可以从数组,列表框等处取得.
::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA,
"c:\\usefile\\usefile.ini");
}
strTemp.Format("%d",nCount);
::WritePrivateProfileString("FileCount","Count",strTemp,"c:\\usefile\\usefile.ini");
file://将文件总数写入,以便读出.
2.读出:
nCount=::GetPrivateProfileInt("FileCount","Count",0,"c:\\usefile\\usefile.ini");
for(i=0;i {strTemp.Format("%d",i);
strTemp="FileName"+strTemp;
::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c:\\usefile\\usefile.ini");
file://使用strTempA中的内容.
}
补充四点:
1.INI文件的路径必须完整,文件名前面的各级目录必须存在,否则写入不成功,该函数返回 FALSE 值.
2.文件名的路径中必须为 \\ ,因为在VC++中, \\ 才表示一个 \ .
3.也可将INI文件放在程序所在目录,此时 lpFileName 参数为: ".\\student.ini".
CFile is the class used for handling Files in MFC. This class can be used for creating, reading, writing and modifying files. It directly provides unbuffered, binary disk input/output services, and it indirectly supports text files and memory files through its derived classes.
CFile - Creating a File:
There are two ways of creating files. One way is to instantiate the CFile object with the file path. This creates the file. The second way is to call the Open function. This also creates the file.
CFile cfile_object( "c:\\test\\codersource_cfile_example.txt", CFile::modeCreate|CFile:: modeReadWrite);
CFile cfile_object;
cfile_object.Open( "c:\\test\\codersource_cfile_example.txt",  CFile::modeCreate|CFile:: modeReadWrite);
The first parameter to both the functions (CFile() constructor and Open()) is the physical path of the file in the disk. The second parameter is an enumerated constant. This specifies the mode of opening the file object. The above constants modeCreate implies "create a new file" and modeReadWrite means "open the file for both reading and writing".
If the file is opened without specifying the mode constant shareDenyNone, this file can be opened in read mode by other programs. This feature will be necessary for text files, logs created by programs. For creating text files we use CFile::typeText and for binary files CFile::typeBinary.
CFile - Writing to a File:
The function Write is used to write data to the files. The sample code is as follows.
CFile cfile_object;
cfile_object.Open( "c:\\test\\codersource_cfile_example.txt", CFile::modeCreate|CFile::modeWrite);
char szSampleText[100];
strcpy(szSampleText, "Sample Text for CFile Write function Example");
cfile_object.Write (szSampleText,100);
If there is any need to write text line by line, it is better to use the class CStdioFile.
CFile - Reading from a file:
The function Read is used to read data from files. The sample code is,
CFile cfile_object;
cfile_object.Open( "c:\\test\\codersource_cfile_example.txt", CFile::modeCreate|CFile::modeWrite);
char szSampleText[100];
UINT lBytesRead = cfile_object.Read (szSampleText,100);
The function returns the number of bytes read from the file. The maximum number of characters read will be the second parameter of the Read function.
CFile - closing the file:
The Close function is used to close the file. But the close function need not be called, as the destructor will automatically call it if the file is open. So when the object goes out of scope, the destructor calls close function.
from:http://www.codersource.net/mfc_cfile.html
CFile的派生类CStdioFile提供了对文件进行流式的操作功能。其中函数void CStdioFile::WriteString( LPCTSTR lpsz )写入一个字符串,需要给字符串lpsz的末尾加上换行标志”\r\n”;函数bool CStdioFile::ReadString(CString &rString )从文件中读取一行,如果文件未读完返回true,否则返回false。比如:写入文件的例子
//创建文件
CStdioFile file;
file.Open("ts.txt",CFile::modeCreate|CFile::modeWrite);
//写入文件
CString str;
str.Format("%s\r\n","hello!I am talkingmute!");
file.Seek(0,CFile::end);
file.WriteString( str );
//关闭文件
file.Close();
比如:读文件的例子
CString strText = “”;
CString szLine = “”;
//打开文件
CStdioFile file;
file.Open("ts.txt",CFile::modeRead);
//逐行读取字符串
while( file.ReadString( szLine ) )
{
strText += szLine;
}
MessageBox(strText);
//关闭文件
file.Close();
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1573774