Windows环境扫描目录下的文件

Windows环境扫描目录下的文件,并输出。

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
#include <windows.h>  

// return the acture count of item in list  
int scanfile(const char *path, char **list)  
{  
	WIN32_FIND_DATA FindFileData;  
	HANDLE hFind = INVALID_HANDLE_VALUE;  
	char DirSpec[MAX_PATH];  // directory specification  
	int i, count;  
	char *ptr;  
  
	// 设置路径  
	strcpy(DirSpec, path);  
  
	count = 0;  
	do  
	{  
		// 扫描文件夹,统计总文件个数  
		hFind = FindFirstFile(DirSpec, &FindFileData);  
		if(hFind == INVALID_HANDLE_VALUE) break;  
  
		count = 0;  
		do  
		{  
			count++;  
		} while(FindNextFile(hFind, &FindFileData) != 0);  
  
		FindClose(hFind);  
  
		// 重新扫描,以便添加到list  
		list[count] = NULL;  
		ptr = (char *)&list[count + 1];  
  
		// 扫描文件夹,统计总文件个数  
		hFind = FindFirstFile(DirSpec, &FindFileData);  
		if(hFind == INVALID_HANDLE_VALUE) break;  
  
		i = 0;  
		do  
		{  
			list[i] = ptr;  
  
			strcpy(ptr, FindFileData.cFileName);  
  
			i++;  
			ptr+= strlen(FindFileData.cFileName) + 1;  
  
		} while(FindNextFile(hFind, &FindFileData) != 0);  
  
		FindClose(hFind);  
  
	} while(0);  
  
	return count;  
}  

int main()  
{  
	static char buffer[1024];  
	char **list = (char **)buffer;  
	 
	int i, count;
	  
	count = scanfile("D:\\*.bmp", list); // 或者不指定扩展名 "D:\\*" 输出所有文件 
	  
	printf("files:[%d]\n", count);  
	for(i = 0; i < count; i++)  
	{  
		printf("[%d]:%s\n", i, list[i]);  
	}  
	  
	system("PAUSE");  

	return 0;  
}

	

输出结果类似下面:

files:[2]
[0]:abc.bmp
[1]:def.bmp
请按任意键继续. . .


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值