Windows下C语言查找文件例子

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;
}

结果截图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值