Windows下C语言查找文件例子
// 2_4.cpp : Defines the entry point for the console application.
//
//=========================================================================
// 作者 : 欧阳文光
// 邮箱 : ssun125@163.com
// 博客 : http://blog.csdn.net/ssun125
// 描述 : c语言文件查找
// 使用 : cmd下search.exe 目录 文件(可以用通配符*、?)(如:search.exe E: *.java)
// 日期 : 2013年01月25日
//=========================================================================
#include "stdafx.h"
#include <STDIO.H>
#include <MALLOC.H>
#include <STRING.H>
#include <windows.h>
//使用链表保存每个找到的文件夹
typedef struct DirList{
char name[256];
DirList * next;
} *LpDirList;
DirList * first, * last;
//往链表中添加节点
void add(char * name)
{
DirList * newDir = (LpDirList)malloc(sizeof(DirList));
strcpy(newDir->name, name);
newDir->next = NULL;
last->next = newDir;
last = newDir;
}
void loopFind(char * dir, char * filename)
{
//printf("层次遍历文件夹...\n");
char searchName[256] = {0};
char nextDir[256] = {0};
strcpy(searchName, dir);
strcat(searchName, "\\**");
//保存找到的文件或文件夹的信息的结构体
WIN32_FIND_DATA findData;
HANDLE hFindFile = FindFirstFile(searchName, &findData);
while (FindNextFile(hFindFile, &findData))
{
if(findData.cFileName[0] == '.') continue;
if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
strcpy(nextDir, dir);
strcat(nextDir, "\\");
strcat(nextDir, findData.cFileName);
add(nextDir);
memset(nextDir, 0x00, sizeof(nextDir));
}
}
//查找符合条件的文件,并输出
char nextFileName[256] = {0};
memset(searchName, 0x00, sizeof(searchName));
strcpy(searchName, dir);
strcat(searchName, "\\");
strcat(searchName, filename);
hFindFile = FindFirstFile(searchName, &findData);
while (FindNextFile(hFindFile, &findData))
{
strcpy(nextFileName, dir);
strcat(nextFileName, "\\");
strcat(nextFileName, findData.cFileName);
printf("%s\n", nextFileName);
}
}
void search(char * dir, char * filename)
{
printf("开始搜索...\n");
first = (LpDirList)malloc(sizeof(DirList));
strcpy(first->name, dir);
first->next = NULL;
last = first;
while (first != NULL)
{
loopFind(first->name, filename);
first = first->next;
}
}
int main(int argc, char* argv[])
{
if(argv[1]==NULL || argv[2]==NULL)
{
printf("请输入目录或文件!\n");
return 0;
}
search(argv[1], argv[2]);
return 0;
}
结果截图: