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