我想检查指定目录中有多少个文件。例如,我将有一个名为resources
的.exe旁边的目录,我想检查一下.txt文件中有多少文件。如何检查文件夹中有多少个文件?
这是如何在Windows中用C++完成的?
我想检查指定目录中有多少个文件。例如,我将有一个名为resources
的.exe旁边的目录,我想检查一下.txt文件中有多少文件。如何检查文件夹中有多少个文件?
这是如何在Windows中用C++完成的?
这取决于操作系统。在Windows上,您可以使用FindFirstFile
和FindNextFile
来枚举目录内容,使用适当的过滤器(如"*.txt"
)。完成后不要致电FindClose
。
在基于Unix的操作系统上,您可以使用opendir(3)
和readdir(3)
来枚举目录内容。你必须自己过滤文件名。完成后别忘记拨打closedir(3)
。
我会使用boost :: filesystem。甚至有一个sample program大部分的工作为你完成。
此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);
}
什么操作系统? – 2012-01-04 20:05:05
100%操作系统依赖。请注意,有些系统可以用C编程,甚至不存在任何类型的过滤系统。如果你在这样的系统上调用fopen,你会得到链接错误! – 2012-01-04 20:10:24
现在标记为Windows,因此它将是FindFirstFile(),FindNextFile()和FindClose()API调用。 – 2012-01-04 20:10:35