要统计文件夹下所有文件(包括子目录文件)的数量,可以使用递归方法来遍历文件夹和子目录。

以下是一个示例代码:

#include <iostream>
#include <windows.h>

int countFiles(const char* folderPath)
{
    int fileCount = 0;
    WIN32_FIND_DATAA findData;
    HANDLE hFind;

    std::string searchPath = folderPath;
    searchPath += '\*';

    hFind = FindFirstFileA(searchPath.c_str(), &findData);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
            {
                if (strcmp(findData.cFileName, ".") != 0 && strcmp(findData.cFileName, "..") != 0)
                {
                    std::string subFolderPath = folderPath;
                    subFolderPath += '\';
                    subFolderPath += findData.cFileName;
                    fileCount += countFiles(subFolderPath.c_str());
                }
            }
            else
            {
                fileCount++;
            }
        } while (FindNextFileA(hFind, &findData));

        FindClose(hFind);
    }

    return fileCount;
}

int main()
{
    const char* folderPath = "C:\Path\To\Folder";
    int fileCount = countFiles(folderPath);
    std::cout << "Total file count: " << fileCount << std::endl;

    return 0;
}

在上面的示例中,countFiles 函数使用 FindFirstFileAFindNextFileA 函数来遍历文件夹下的文件和子目录。如果找到一个子目录,则递归调用 countFiles 函数来统计子目录中的文件数量。如果找到一个文件,则增加文件计数器。最后,返回文件计数器的值。

main 函数中,可以将要统计的文件夹路径传递给 countFiles 函数,并打印出文件数量。

注意:示例中使用的是 ANSI 版本的 Windows API 函数(FindFirstFileAFindNextFileA)。如果需要支持 Unicode 路径或文件名,请使用对应的 Unicode 版本(FindFirstFileWFindNextFileW)。


原文地址: https://www.cveoy.top/t/topic/pY9W 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录