永发信息网

VC判断文件是否存在

答案:2  悬赏:50  手机版
解决时间 2021-01-30 16:44
  • 提问者网友:记得曾经
  • 2021-01-30 01:06
VC判断文件是否存在
最佳答案
  • 五星知识达人网友:山有枢
  • 2021-01-30 01:32
推荐实例例:
if(::GetFileAttributes(m_filename)==-1){//文件不存在}else{//文件存在}
1. 使用_access函数,函数原型为 int _access( const char *path, int mode );
2. 使用CreateFile函数,函数原型为: HANDLE CreateFile( LPCTSTR lpFileName, // pointer to name of the file DWORD dwDesiredAccess, // access (read-write) mode DWORD dwShareMode, // share mode LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes DWORD dwCreationDisposition, // how to create DWORD dwFlagsAndAttributes, // file attributes HANDLE hTemplateFile // handle to file with attributes to // copy );
3. 使用FindFirstFile函数,函数原型为: HANDLE FindFirstFile( LPCTSTR lpFileName, // pointer to name of file to search for LPWIN32_FIND_DATA lpFindFileData // pointer to returned information );
4. 使用GetFileAttributes函数,函数原型如下: DWORD GetFileAttributes( LPCTSTR lpFileName // pointer to the name of a file or directory );
5. 使用Shell Lightweight Utility APIs函数 PathFileExists()专门判断文件和目录时否存在的函数文件名可读性比较强还可以判断目录是否存在 Header: Declared in Shlwapi.h Import Library: Shlwapi.lib 以上的各种方法供参考,函数具体用法需参见MSDN
全部回答
  • 1楼网友:迟山
  • 2021-01-30 02:06

用mfc类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表示是最后一个文件。

=======================我自己写了个测试,查找d盘根目录下api.chm是否存在成功,完整代码如下:

void cfindfiletest1dlg::onbnclickedbutton1() { // todo: 在此添加控件通知处理程序代码 cfilefind ff; bool isfile=ff.findfile(_t("d:\\*.*")); while (isfile) { isfile=ff.findnextfilew(); if (ff.getfilename().compare(l"api32.chm")==0) { getdlgitem(idc_static)->setwindowtext(ff.getfilename()); break; } sleep(20); } }

若对你有用请采纳,我做团长任务,谢谢!

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯