原文:https://www.cnblogs.com/collectionne/p/6815924.html
程序代码
- 遍历目录下的所有文件
#include <iostream>
#include <cstring> // for strcat()
#include <io.h>
using namespace std;
void listFiles(const char * dir);
int main()
{
char dir[200];
cout << "Enter a directory (ends with \'\\\'): ";
cin.getline(dir, 200);
strcat(dir, "*.*"); // 在要遍历的目录后加上通配符
listFiles(dir);
return 0;
}
void listFiles(const char * dir)
{
intptr_t handle;
_finddata_t findData;
handle = _findfirst(dir, &findData); // 查找目录中的第一个文件
if (handle == -1)
{
cout << "Failed to find first file!\n";
return;
}
do
{
if (findData.attrib & _A_SUBDIR
&& strcmp(findData.name, ".") == 0
&& strcmp(findData.name, "..") == 0
) // 是否是子目录并且不为"."或".."
cout << findData.name << "\t<dir>\n";
else
cout << findData.name << "\t" << findData.size << endl;
} while (_findnext(handle, &findData) == 0); // 查找目录中的下一个文件
cout << "Done!\n";
_findclose(handle); // 关闭搜索句柄
}
程序遍历目录下的所有文件/目录,如果是文件则输出文件大小。
注意_findnext()函数成功返回0,因此要加上==0或!=-1进行判断,不能省略。
此外还有一个值得注意的地方:
if (findData.attrib & _A_SUBDIR
&& strcmp(findData.name, ".")
&& strcmp(findData.name, "..")
)
使用_findfirst()、_findnext()进行搜索时,可能会得到”.”和”..”两个文件夹名。这两个值可以忽略。
遍历目录中的所有文件
注意是“目录中”而不是“目录下”,这个程序将会遍历一个目录里包含的所有文件。
#include <iostream>
#include <cstring> // for strcpy(), strcat()
#include <io.h>
using namespace std;
void listFiles(const char * dir);
int main()
{
char dir[200];
cout << "Enter a directory: ";
cin.getline(dir, 200);
listFiles(dir);
return 0;
}
void listFiles(const char * dir)
{
char dirNew[200];
strcpy(dirNew, dir);
strcat(dirNew, "\\*.*"); // 在目录后面加上"\\*.*"进行第一次搜索
intptr_t handle;
_finddata_t findData;
handle = _findfirst(dirNew, &findData);
if (handle == -1) // 检查是否成功
return;
do
{
if (findData.attrib & _A_SUBDIR)
{
if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
continue;
cout << findData.name << "\t<dir>\n";
// 在目录后面加上"\\"和搜索到的目录名进行下一次搜索
strcpy(dirNew, dir);
strcat(dirNew, "\\");
strcat(dirNew, findData.name);
listFiles(dirNew);
}
else
cout << findData.name << "\t" << findData.size << " bytes.\n";
} while (_findnext(handle, &findData) == 0);
_findclose(handle); // 关闭搜索句柄
}