遍历文件夹下所有文件的方法c和c++实现

 C++代码实现如下:

void EnumFiles(const char *directory, int *count, char **result, int flag)//flag:2 bmp  1 bin
{
	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;
	char pattern[MAX_PATH];
	int i = 0;
	char dir[MAX_PATH];
	// 开始查找
	strcpy(pattern, directory);
	strcat(pattern, "\\*.*");
	hFind = FindFirstFile(pattern, &FindFileData);

	if (hFind == INVALID_HANDLE_VALUE)
	{
		*count = 0;
	}
	else
	{
		do
		{
			if (flag == 0 && i >= MAX_IMG_NUM)
				continue;
			if ((flag == 1 || flag == 2) && i >= MAX_IMG_NUM)
				continue;
			if (strcmp(FindFileData.cFileName, ".") == 0 || strcmp(FindFileData.cFileName, "..") == 0)
				continue;
			memset(dir, 0, MAX_PATH);
			strcpy(dir, directory);
			strcat(dir, "\\");
			strcat(dir, FindFileData.cFileName);
			if (flag == 1)
			{
				int l = strlen(dir);
				if (dir[l - 1] == 'n' && dir[l - 2] == 'i' && dir[l - 3] == 'b')
				{
					strcpy(result[i++], dir);
				}
				else
					continue;
			}
			else if (flag == 2)
			{
				int l = strlen(dir);
				if (dir[l - 1] == 'p' && dir[l - 2] == 'm' && dir[l - 3] == 'b')
				{
					strcpy(result[i++], dir);
				}
				else
					continue;
			}
			else
				strcpy(result[i++], dir);
		} while (FindNextFile(hFind, &FindFileData) != 0);
	}
	// 查找结束
	FindClose(hFind);
	// 复制到结果中
	*count = i;
}

 

C代码实现如下:

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
#define MAX_PATH_LEN 256  
  
int main(int argc, char *argv[]) {  
    char path[MAX_PATH_LEN];  
    char *ptr;  
    DIR *dir;  
    struct dirent *entry;  
    int i, count = 0;  
  
    if (argc < 2) {  
        printf("Usage: %s <directory>\n", argv[0]);  
        exit(1);  
    }  
  
    strcpy(path, argv[1]);  
    printf("path:%s\n",path);
    dir = opendir(path);  
    if (!dir) {  
        printf("Error opening directory %s\n", path);  
        exit(1);  
    }  
  
    while ((entry = readdir(dir)) != NULL) {  
        if (entry->d_type == DT_REG) {  
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {  
                continue;  
            }  
            if (strstr(entry->d_name, ".bmp") != NULL) {  
                printf("%s/%s\n", path, entry->d_name);  
                count++;  
            }  
        }  
    }  
    closedir(dir);  
  
    printf("Total %d .bmp files found in directory %s\n", count, argv[1]);  
    return 0;  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值