VC.遍历文件夹中的文件

1、VC下遍历文件夹中的所有文件的几种方法 - 年少要轻狂 - CSDN博客.html(https://blog.csdn.net/wllmsdn/article/details/27220999

2、

3、测试代码:

  3.1、FindFile.cpp  FindFile_01(..) 使用的是 WindowsAPI,FindFile_02(..)使用的是 C标准函数

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

#define LEN 1024
//int FileCount = 0;

// 深度优先递归遍历目录中所有的文件
int FindFile_01(char* _pcPath)
{
    int iFileCount = 0;

    WIN32_FIND_DATAA FindData;
    HANDLE hError;
    
    char ccFilePathName[LEN];
    // 构造路径
    char ccFullPathName[LEN];
    strcpy(ccFilePathName, _pcPath);
    strcat(ccFilePathName, "\*.*");
    hError = FindFirstFileA(ccFilePathName, &FindData);
    if (hError == INVALID_HANDLE_VALUE)
    {
        printf("搜索失败!");
        return 0;
    }

    while(::FindNextFileA(hError, &FindData))
    {
        // 过虑.和..
        if (strcmp(FindData.cFileName, ".") == 0
            || strcmp(FindData.cFileName, "..") == 0 )
        {
            continue;
        }
        printf("%s
", FindData.cFileName);

        // 构造完整路径
        sprintf(ccFullPathName, "%s\%s", _pcPath, FindData.cFileName);
        // 输出本级的文件
        //printf("%s
", ccFullPathName);
        iFileCount ++;
        if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            int iRst = FindFile_01(ccFullPathName);
            iFileCount += iRst;
        }
    }
    return iFileCount;
}

// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

#include<io.h>
#include<iostream>
#include<string>
using namespace std;

// ZC: findfile("F:\duquceshi", "\*.*");
int FindFile_02(string _strPath, string _strMode)
{
    int iFileCount = 0;

    _finddata_t file;
    intptr_t h;
    string OnePath = _strPath + _strMode;
    h = _findfirst(OnePath.c_str(), &file);
    if (h == -1L)
    {
        cout << "can not match the folder path" << endl;
        system("pause");
    }
    do
    {
        //判断是否有子目录  
        if (file.attrib & _A_SUBDIR)
        {
            printf("%s
", file.name);

            //判断是否为"."当前目录,".."上一层目录
            if ((strcmp(file.name, ".") != 0) && (strcmp(file.name, "..") != 0))
            {
                string newPath = _strPath +"\" + file.name;
                iFileCount ++;
                int iRst = FindFile_02(newPath, _strMode);
                iFileCount += iRst;
            }
        }
        else
        {
            cout << file.name << " " << endl;
        }
    }
    while (_findnext(h, &file) == 0);

    _findclose(h);
    return iFileCount;
}

  3.2、main.cpp  调用FindFile_0?(...)

#include <windows.h>
#include <iostream>
using namespace std;

int FindFile_01(char* _pcPath);
int FindFile_02(string _strPath, string _strMode);

void main()
{
//    FindFile_01("F:\__SanHeng\opencv-2.4.13.6-vc14\build\x86\vc14\lib");
    FindFile_02("F:\__SanHeng\opencv-2.4.13.6-vc14\build\x86\vc14\lib", "\*.*");

    system("pause");
}

4、

5、

原文地址:https://www.cnblogs.com/cppskill/p/9884107.html