CFileFind类
MFC类CFileFind执行本地文件查找,是CGopherFileFind和CFtpFileFind的基类;后两类用于Internet文件查找。CFileFind包括的成员函数有开始查找、定位文件、返回标题名或路径等。对于Internet查找来说,GetFileURL返回文件的URL。
CFileFind是为另两类查找特殊服务器设计的MFC类的基类,CGopherFileFind在Gopher服务器上工作,CFtpFileFind在FTP服务器上工作,这些类为用户查找文件提供了一种无缝机制,与服务器协议、文件类型、地点、本地机器或远程服务器无关。
以下代码将当前目录下的文件枚举出来并打印每个文件名:
CFileFindfinder
BOOLbWorking = finder.FindFile("*.*");
while(bWorking)
{
bWorking =finder.FindNextFile( );
cout<<(LPCTSTR) finder.GetFileName( ) <<endl;
}
为使示例简单,此代码使用标准C++库函数cout类,cout行可由调用CListBox::AddString来代替。
#include <afx.h>
请参阅:CFtpFileFind,CGopherFileFind,CInternetFile,CGopherFile,CHttpFile
1. CFileFind:构造一个CFileFind对象。示例如下:
See the examplefor CFileFind::GetFileName.
属性函数
2. GetCreationTime:获取文件创建时间。示例如下:
// Thiscode fragment prints out a very verbose directory
// listingfor all the files in the root directory on the
// C:drive. After the file's name, each attribute of the
// file isprinted, as are the creation, last access, and
// lastwrite times.
CFileFind finder;
BOOL bWorking =finder.FindFile(_T("C:\\*.*"));
while (bWorking)
{
bWorking = finder.FindNextFile();
_tprintf_s(_T("%s\n\t"),(LPCTSTR) finder.GetFileName());
_tprintf_s(_T("%c"),finder.IsArchived() ? 'A' : 'a');
_tprintf_s(_T("%c"),finder.IsCompressed() ? 'C' : 'c');
_tprintf_s(_T("%c"),finder.IsHidden() ? 'H' : 'h');
_tprintf_s(_T("%c"),finder.IsNormal() ? 'N' : 'n');
_tprintf_s(_T("%c"),finder.IsReadOnly() ? 'R' : 'r');
_tprintf_s(_T("%c"),finder.IsSystem() ? 'S' : 's');
_tprintf_s(_T("%c"),finder.IsTemporary() ? 'T' : 't');
_tprintf_s(_T("\t%I64ubyte(s)\n"), finder.GetLength());
CTime tempTime;
CString str;
_tprintf_s(_T("\tCreated : "));
if (finder.GetCreationTime(tempTime))
{
str = tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\tLast Access:"));
if (finder.GetLastAccessTime(tempTime))
{
str = tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\tLast Write :"));
if (finder.GetLastWriteTime(tempTime))
{
str =tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\n"));
}
3. GetFileName:获取找到文件的名字,包括扩展名。示例如下:
CFileFindfinder;
staticconst TCHAR szFileToFind[] = _T("C:\\WINDOWS\\SYSTEM.INI");
BOOLbResult = finder.FindFile(szFileToFind);
if(bResult)
{
finder.FindNextFile();
cout << "Root of " <<szFileToFind;
cout << " is " <<(LPCTSTR) finder.GetRoot();
cout << endl;
cout << "Title of " <<szFileToFind;
cout << " is " <<(LPCTSTR) finder.GetFileTitle();
cout << endl;
cout << "Path of " <<szFileToFind;
cout << " is " <<(LPCTSTR) finder.GetFilePath();
cout << endl;
cout << "URL of " <<szFileToFind;
cout << " is " <<(LPCTSTR) finder.GetFileURL();
cout << endl;
cout << "Name of " <<szFileToFind;
cout << " is " <<(LPCTSTR) finder.GetFileName();
cout << endl;
finder.Close();
}
else
cout << "You have no "<< szFileToFind << " file." << endl;
4. GetFilePath:获取找到文件的全路径。示例如下:
See theexample for CFileFind::GetFileName.
5. GetFileTitle:获取找到文件的标题,标题不包括扩展内容。示例如下:
See theexample for CFileFind::GetFileName.
6. GetFileURL:获取找到文件的URL,包括文件路径。示例如下:
See theexample for CFileFind::GetFileName.
7. GetLastAccessTime:获取文件最后一次打开的时间。示例如下:
See theexample for CFileFind::GetLength.
8. GetLastWriteTime:获取文件最后改变和存储的时间。示例如下:
See theexample for CFileFind::GetLength.
9. GetLength:获取找到文件的长度,以字节为单位。示例如下:
// Thiscode fragment prints out a very verbose directory
// listingfor all the files in the root directory on the
// C:drive. After the file's name, each attribute of the
// file isprinted, as are the creation, last access, and
// lastwrite times.
CFileFind finder;
BOOL bWorking =finder.FindFile(_T("C:\\*.*"));
while (bWorking)
{
bWorking = finder.FindNextFile();
_tprintf_s(_T("%s\n\t"),(LPCTSTR) finder.GetFileName());
_tprintf_s(_T("%c"),finder.IsArchived() ? 'A' : 'a');
_tprintf_s(_T("%c"),finder.IsCompressed() ? 'C' : 'c');
_tprintf_s(_T("%c"),finder.IsHidden() ? 'H' : 'h');
_tprintf_s(_T("%c"),finder.IsNormal() ? 'N' : 'n');
_tprintf_s(_T("%c"),finder.IsReadOnly() ? 'R' : 'r');
_tprintf_s(_T("%c"),finder.IsSystem() ? 'S' : 's');
_tprintf_s(_T("%c"),finder.IsTemporary() ? 'T' : 't');
_tprintf_s(_T("\t%I64ubyte(s)\n"), finder.GetLength());
CTime tempTime;
CString str;
_tprintf_s(_T("\tCreated : "));
if (finder.GetCreationTime(tempTime))
{
str =tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\tLast Access:"));
if (finder.GetLastAccessTime(tempTime))
{
str =tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\tLast Write :"));
if (finder.GetLastWriteTime(tempTime))
{
str =tempTime.Format(_T("%c"));
_tprintf_s(_T("%s\n"),(LPCTSTR) str);
}
else
_tprintf_s(_T("(unavailable)\n"));
_tprintf_s(_T("\n"));
}
10. GetRoot:获取找到文件的根目录。示例如下:
See theexample for CFileFind::GetFileName.
11. IsArchived:检验文件是否是档案。示例如下:
See theexample for CFileFind::GetLength.
12. IsCompressed:检验文件是否是压缩文件。示例如下:
See theexample for CFileFind::GetLength.
13. IsDirectory:检验文件是否是目录。示例如下:
#include<afxwin.h>
#include<iostream>
usingnamespace std;
voidRecurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\\*.*");
// start working for files
BOOL bWorking =finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursivelysearch it
if (finder.IsDirectory())
{
CString str = finder.GetFilePath();
cout << (LPCTSTR) str <<endl;
Recurse(str);
}
}
finder.Close();
}
int main()
{
if (!AfxWinInit(GetModuleHandle(NULL), NULL,GetCommandLine(), 0))
cout << "panic!" <<endl;
else
Recurse(_T("C:"));
}
14. IsDots:查看文件名是否是包含"."或"..",以表明它的确是一个目录。示例如下:
See theexample for CFileFind::IsDirectory.
15. IsHidden:检验文件是否是隐藏文件。示例如下:
See theexample for CFileFind::GetLength.
16. IsNormal:检验文件是否是常规文件(无其它属性)。示例如下:
See theexample for CFileFind::GetLength.
17. IsReadOnly:检验文件是否是只读文件。示例如下:
See theexample for CFileFind::GetLength.
18. IsSystem:检验文件是否是系统文件。示例如下:
See theexample for CFileFind::GetLength.
19. IsTemporary:检验文件是否是临时文件。示例如下:
See theexample for CFileFind::GetLength.
20. MatchesMask:指定要找的文件的属性。示例如下:
//cfilefind_matchesmask.cpp
// compilewith: /W0
// Thiscode fragment shows all of the files in the root directory
// of driveC: which have either the hidden attribute or the system
// attribute,or both.
#include<string.h>
#include<afx.h>
intmain(int argc, char* argv[])
{
CFileFind finder;
BOOL bWorking =finder.FindFile(_T("C:\\*.*"));
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.MatchesMask(FILE_ATTRIBUTE_HIDDEN|
FILE_ATTRIBUTE_SYSTEM))
{
_tprintf_s(_T("%s\n"),(LPCTSTR) finder.GetFileName());
}
}
return 0;
}
21. Close:关闭查找请求。示例如下:
See theexample for CFileFind::GetFileName.
22. CloseContext:通过当前搜索句柄关闭指定文件。示例如下:
Closes thefile specified by the current value of the search handle. Override thisfunction to change the default behavior.
You mustcall the FindFile or FindNextFile functionsat least once to retrieve a valid search handle.The FindFile and FindNextFile functions use the searchhandle to locate files with names that match a given name.
23. FindFile:查找目录中的指定文件。示例如下:
See theexample for CFileFind::IsDirectory.
24. FindNextFile:在调用FindFile之后调用,用于继续下一查找。示例如下:
See theexample for CFileFind::IsDirectory.
CFileFind类
1. CFileFind类的声明文件保存在afx.h头文件中。
2. 该类的实现的功能:执行本地文件的查找(查找某个具体的文件,查找某类文件x*.x*,查找所有文件*.*)
3. CFileFind类是CGopherFileFind和CFtpFileFind类的基类。
4. CFileFind类的构造函数::CFileFind()和关闭函数::Close()我会成对使用。
5. CFileFind类的成员函数我根据其操作特性划分为3类:查找操作类. 获得文件属性类. 判断文件属性类。(下面我先进行函数罗列并没有完整的描述函数的参数)
查找操作类
::FindFile();
::FindNextFile();
获得文件属性类
::GetCreationTime();
::GetLastAccessTime();
::GetLastWriteTime();
::GetFileName();
::GetRoot();
::GetFilePath();
::GetFileTitle();
::GetFileURL();
::GetLength();
判断文件属性类
::IsArchived();
::IsCompressed();
:IsDirectory();
::IsDots();
::IsHidden();
::IsNormal();
::IsReadOnly();
::IsSystem();
::IsTemporary();
::MatchesMask();
6. CFileFind类中成员函数使用应注意的顺序
在创建了CFileFind对象后,先执行::FindFile()函数,然后执行::FindNextFile(),然后选择执行(获得文件属性类)的函数或者(判断文件属性类)函数。
7. CFileFind类成员函数的详细分析
virtual BOOL FindFile(LPCTSTR pstrName = null,DWORD dwUnused = 0);
该函数若返回非0 则表明执行成功,0 则表明执行不成功。
pstrName:需要查找的文件名,例:“E://编程工具//VC++//MFC例子.rar”,“E://编程工具//VC++//MFC*.rar”,“E://编程工具//VC++//*.*”,也可以是NULL表示“*.*”。
dwUnused:必须为0
virtual BOOL FindNextFile();
该函数返回值非0 还有符合条件的文件, 0表示是最后一个文件。
virtual BOOL GetCreationTime(FILETIME *pFileTime) const;
virtual BOOLGetCreationTime(CTime& refTime) const;
该函数用来获得查找到的某个文件的创建时间,返回值非0 获得创建时间成功操作,0表示执行获得创建时间失败或者FindNextFile()没有被执行的时候。
FILETIME *:容纳时间的结构指针
CTime&:容纳时间的对象地址
此处介绍:FILETIME和CTime相互转换的处理方法:
FILETIME转CTime的方法:
A. CTime对象在初始化时可以传递FILETIME结构
FILETIME ft;
CTime time(ft);
B. 将FILETIME转换为SYSTEMTIME,然后CTime对象在初始化时可以传递SYSTEMTIME结构
FILETIME ft;
SYSTEMTIME st;
BOOL bSuccess = ::FileTimeToSystemTime(&ft ,&st);
CTime time(st);
CTime转FILETIME方法:
CTime time(CTime::GetCurrentTime());
SYSTEMTIME st;
time.GetAsSystemTime(st);
FILETIME ft;
::SystemTimeToFileTime(&st,&ft);
virtual BOOL GetLastAccessTime(FILETIME *pFileTime) const;
virtual BOOL GetLastAccessTime(CTime& refTime) const;
该函数用来获得某个文件最后被访问的时间,非0表示执行成功,0表示执行失败或者FindNextFile()函数没有执行的时候。
virtual BOOL GetLastWriteTime(FILETIME *pFileTime) const;
virtual BOOL GetLastWriteTime(CTime& refTime) const;
该函数用来获得某个文件最后被访问的时间,非0表示执行成功,0表示执行失败或者FindNextFile()函数没有执行的时候。
virtual CString GetFilePath() const;
该函数用来获得查找到的文件绝对路径,必须在执行了FindNextFile()后该函数才能执行成功。
返回的结果是CString对象,例“E://编程工具//VC++//MFC.rar”
virtual CString GetFileName() const;
该函数用来获得查找到的文件的全称,必须在执行了FindNextFile()后该函数才能执行成功。
返回的结果是CString对象,例“MFC.rar”
virtual CString GetFileTitle() const;
该函数用来获得查找到的文件的名称,必须在执行了FindNextFile()后该函数才能执行成功。
返回的结果是CString对象,例“MFC”
virtual CString GetRoot() const;
该函数用来获得查找到的文件的根目录,必须在执行了FindNextFile()后该函数才能执行成功。
返回的结果是CString对象,例“E://编程工具//VC++//”
virtual CString GetFileURL() const;
该函数用来获得查找到的文件的URL路径,必须在执行了FindNextFile()后该函数才能执行成功。
返回的结果是CString对象,例“file://E://编程工具//VC++//MFC.rar”
DWORD GetLength() const;
该函数返回值获得查找到的文件的长度,必须在执行了FindNextFile()后该函数才能执行成功。
BOOL IsArchived() const;
该函数用来判断查找的文件属性是否是档案文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsCompressed() const;
该函数用来判断查找的文件属性是否是压缩文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsDirectory() const;
该函数用来判断查找的文件属性是否是路径文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsDots() const;
该函数用来判断查找的文件属性是否是“.”,“..”,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsHidden() const;
该函数用来判断查找的文件属性是否隐藏文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsNormal() const;
该函数用来判断查找的文件属性是否正常文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsReadOnly() const;
该函数用来判断查找的文件属性是否只读文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsSystem() const;
该函数用来判断查找的文件属性是否系统文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL IsTemporary() const;
该函数用来判断查找的文件属性是否临时文件,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
BOOL MatchesMask(DWORD dwMask) const;
该函数用来判断查找的文件的综合属性,非0表示是,0表示不是。必须在执行了FindNextFile()后该函数才能执行成功
dwMask参数的使用方法:几种文件属性采用或运算(|)
文件属性的结构定义:
FILE_ATTRIBUTE_ARCHIVE:档案文件
FILE_ATTRIBUTE_COMPRESSED:压缩文件
FILE_ATTRIBUTE_DIRECTORY:路径文件
FILE_ATTRIBUTE_NORMAL:正常文件
FILE_ATTRIBUTE_READONLY:只读文件
FILE_ATTRIBUTE_SYSTEM:系统文件
FILE_ATTRIBUTE_TEMPORARY:临时文件
FILE_ATTRIBUTE_HIDDEN:隐藏文件
CFileFind的使用方法
去年十月份,因项目需要,做了UD上传功能,用到了CFileFind类,现在回顾一下CFileFind类的使用方法。
1. 遍历一个目录:
CFileFind ff;
if(strUDDir.Right(1) != "//")strUDDir +="//";
strUDDir += "*.*";
BOOL res = ff.FindFile(strUDDir);
while(res)
{
res = ff.FindNextFile();
// 不遍历子目录
if(!ff.IsDirectory() &&!ff.IsDots())
{
…//在这里写需要的代码
}
}
ff.Close(); // 不要忘记关闭
2. 成员函数的使用
于不常使用CFileFind类的人,对GetfilePath()和GetFileName()等函数得到的值很容易混淆,我写了一段代码,看执行后的结果便可知道各函数返回的结果(看不懂没关系,后面还有个例子)。
l_strFilePath = ff.GetFilePath();
l_strFileName = ff.GetFileName();
l_nPoint = l_strFileName.ReverseFind('.'); // 因为文件名中可能出现多个'.'所以用 ReverseFind而不用Find?
l_nLength = l_strFileName.GetLength();
l_strFileExt = l_strFileName.Right(l_nLength - l_nPoint - 1);
l_strFileTitle = ff.GetFileTitle();
l_strFileUrl = ff.GetFileURL();
l_strFileRoot = ff.GetRoot();
l_dwLength = ff.GetLength();
得到的结果:
Filepath: f:/hoho/hzyong2008.doc
FileName: hzyong2008.doc
FileExe: doc
nFileTitle: hzyong2008
FileUrl: file://f:/hoho/hzyong2008.doc
FileRoot: f:/hoho
FileLength: 603648
对照代码与上面的结果便可以知道各个函数的功能了吧!还有些成员函数没介绍比如GetLastWriteTime(CTime& refTime ),自己慢慢体会去吧。
3. 文件备份
TRY
{
CopyFile(strFullName, strBackDir+ strFileName, FALSE); // copy file
DeleteFile(strFullName); //delete source file
}
CATCH (CFileException, pEx)
{
AfxMessageBox("UD文件备份失败");
}
END_CATCH
4. 附
我写了段代码做了个小试验来试用上面介绍到的函数:主要代码与执行结果如下:
CFileFind ff;
CString l_strFilePath;
CString l_strFileName;
CString l_strFileExt;
CString l_strFileTitle;
CString l_strFileUrl;
CString l_strFileRoot;
DWORD l_dwLength;
CString l_strResult;
int l_nPoint;
int l_nLength;
m_strResult = "";
CString l_strDir = m_strDir; // m_strDir = "f://hoho";
if(l_strDir.Right(1) != "//")
l_strDir += "//";
l_strDir += "*.*";
BOOL res = ff.FindFile(l_strDir);
while(res)
{
res = ff.FindNextFile();
// 不遍历子目录
if(!ff.IsDirectory() && !ff.IsDots())
{
l_strFilePath = ff.GetFilePath();
l_strFileName = ff.GetFileName();
l_nPoint = l_strFileName.ReverseFind('.'); // 因为文件名中可能出现多个'.'所以用ReverseFind而不用Find?
l_nLength = l_strFileName.GetLength();
l_strFileExt = l_strFileName.Right(l_nLength - l_nPoint - 1);
l_strFileTitle = ff.GetFileTitle();
l_strFileUrl = ff.GetFileURL();
l_strFileRoot = ff.GetRoot();
l_dwLength = ff.GetLength();
l_strResult.Format("Filepath: %s/r/nFileName: %s/r/nFileExe:%s/r/nnFileTitle: %s/r/nFileUrl: %s/r/nFileRoot: %s/r/nFileLength:%d/r/n/r/n", l_strFilePath, l_strFileName, l_strFileExt, l_strFileTitle,l_strFileUrl, l_strFileRoot, l_dwLength);
m_strResult += l_strResult;
}
}
ff.Close();