请教一个win32 API 问题, 遍历文件夹。

xiangchendub 2010-06-24 12:55:55
其实很简单,就是不知道为啥抓不到句柄。

int main(void)
{
//char path[] = "C:\\*.*";

WIN32_FIND_DATA find_data;
HANDLE search_handle;

search_handle = FindFirstFile("C:\\*.*", &find_data);
if(search_handle != INVALID_HANDLE_VALUE) {
//do something here
}

FindClose(search_handle);
}

运行到FindFirstFile 后,抓不到句柄,下面if 直接跳出了。
请朋友们帮忙看一下。谢谢。

用的VS2005
...全文
217 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
mingcsharp 2010-06-24
  • 打赏
  • 举报
回复
INVALID_HANDLE_VALUE是否有错?
chaoliu1024 2010-06-24
  • 打赏
  • 举报
回复
一段完整的代码
#include <stdio.h>
#include <windows.h>

#define FILEILTER "*.*"

BOOL IsRoot(LPCTSTR lpszPath)
{
TCHAR szRoot[4];
wsprintf(szRoot, "%c:\\", lpszPath[0]);
return (lstrcmp(szRoot, lpszPath) == 0);
}


void FindInAll(LPCTSTR lpszPath)
{
TCHAR szFind[MAX_PATH];
lstrcpy(szFind, lpszPath);
if (!IsRoot(szFind))
lstrcat(szFind, "\\");
lstrcat(szFind, FILEILTER); // 找所有文件
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(szFind, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return;

do
{
if (wfd.cFileName[0] == '.')
continue; // 过滤这两个目录
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
TCHAR szFile[MAX_PATH];
if (IsRoot(lpszPath))
wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName);
else
{
wsprintf(szFile, "%s\\%s", lpszPath, wfd.cFileName);
FindInAll(szFile); // 如果找到的是目录,则进入此目录进行递归
}
}
else
{
TCHAR szFile[MAX_PATH];
if (IsRoot(lpszPath))
{
wsprintf(szFile, "%s%s", lpszPath, wfd.cFileName);
}
else
{
wsprintf(szFile, "%s\\%s", lpszPath, wfd.cFileName);
printf("%s\n",szFile);
}
// 对文件进行操作
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind); // 关闭查找句柄

}
int main(int argc, char* argv[])
{
char findFile[64]="d:";//要查找的目录
FindInAll(findFile);
getchar();
return 0;
}
hastings 2010-06-24
  • 打赏
  • 举报
回复
我可以的哎。
5楼的好厉害。
赵4老师 2010-06-24
  • 打赏
  • 举报
回复
遍历文件夹我只用
system("cmd /c dir /a-d /b /s c:\\mydir\\*.* >c:\\allfiles.txt");
//然后读文件c:\\allfiles.txt的内容
xiangchendub 2010-06-24
  • 打赏
  • 举报
回复
都不行,继续等吧,谢谢楼上各位
reality 2010-06-24
  • 打赏
  • 举报
回复
CString strFileName;
CFileFind finder;
CString szDir;
szDir.Format("%s\\*.*",SrcPath);
BOOL bWorking = finder.FindFile(szDir);
while(bWorking)
{
bWorking = finder.FindNextFile();
strFileName=finder.GetFileName();
if(finder.IsDirectory() && !finder.IsDots())
ProcessCompany(strFileName);
}
试试这个
npuhuxl 2010-06-24
  • 打赏
  • 举报
回复
你换换其他文件夹试试。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧