如何检查文件夹中有多less个文件?

我想检查指定目录中有多less个文件。 例如,我将有一个目录旁边的.exe名为resources ,我想检查有多less.txt文件位于它。

如何在Windows中使用C ++?

这取决于操作系统。 在Windows上,您可以使用FindFirstFileFindNextFile枚举目录内容,使用适当的过滤器(如"*.txt" 。 完成后不要致电FindClose

在基于Unix的操作系统上,可以使用opendir(3)readdir(3)来枚举目录内容。 你必须自己过滤文件名。 当你完成时,不要忘记给closedir(3)打电话。

我会使用boost :: filesystem。 甚至有一个示例程序 ,为您完成大部分工作。

此MS Windows代码列出了C:中的所有.txt文件。 要列出所有其他文件, strcpy(DirSpec, "c:\\*.txt")更改为strcpy(DirSpec, "c:\\*")

 #include <stdio.h> #include <stdlib.h> #define _WIN32_WINNT 0x0501 #include <windows.h> #define BUFSIZE MAX_PATH int main(int argc, char *argv[]) { WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError; LPSTR DirSpec; unsigned int nFiles=0; DirSpec = (LPSTR) malloc (BUFSIZE); strcpy(DirSpec, "c:\\*.txt"); printf ("Current directory : %s\n\n", DirSpec); hFind = FindFirstFile(DirSpec, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf ("incorrect Handle : %u.\n", GetLastError()); return (-1); } else { printf ("%s\n", FindFileData.cFileName); while ( FindNextFile (hFind, &FindFileData) != 0) { nFiles++; printf ("%s\n", FindFileData.cFileName); } dwError = GetLastError(); FindClose(hFind); printf ("\n %d files found.\n\n", nFiles); if (dwError != ERROR_NO_MORE_FILES) { printf ("FindNextFile Error.\n", dwError); return (-1); } } free(DirSpec); return (0); }