当我们需要对一个文件夹下的所有文件进行遍历时,可以使用递归方式或者非递归方式实现。下面分别详细讲解一下这两种实现方式。
递归遍历文件夹
递归遍历文件夹的实现方式是通过调用自身函数来实现,具体步骤如下:
- 定义一个函数,该函数接收一个文件夹路径作为参数。
- 打开这个文件夹,遍历其中的所有文件和文件夹。
- 对于每个文件夹,调用该函数来再次遍历其中的文件和文件夹。
- 对于每个文件,进行相应的操作。
下面是C++程序示例:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<direct.h>
#include<io.h>
using namespace std;
void RecursiveTraverseFolder(const char*);
int main()
{
RecursiveTraverseFolder("C:\\Users\\Desktop\\test");
return 0;
}
void RecursiveTraverseFolder(const char* folderPath)
{
struct _finddata_t file;
intptr_t handle;
char path[100];
// 匹配所有文件和文件夹
sprintf(path, "%s\\*.*", folderPath);
handle = _findfirst(path, &file);
if (handle == -1)
{
cout << "查找文件失败" << endl;
return;
}
do
{
if (file.attrib & _A_SUBDIR) // 判断是否是文件夹
{
if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) // 排除 . 和 ..
{
sprintf(path, "%s\\%s", folderPath, file.name);
cout << path << endl; // 对文件夹进行相应操作
RecursiveTraverseFolder(path); // 递归遍历
}
}
else // 文件
{
sprintf(path, "%s\\%s", folderPath, file.name);
cout << path << endl; // 对文件进行相应操作
}
} while (_findnext(handle, &file) == 0);
_findclose(handle);
}
非递归遍历文件夹
非递归遍历文件夹的实现方式是使用一个栈来存储文件夹的路径,具体步骤如下:
- 定义一个栈,用于存储文件夹路径。
- 将要遍历的文件夹路径入栈。
- 循环遍历所有入栈的文件夹,对于每个文件夹遍历其中的文件和文件夹并进行相应的操作。
- 每次遍历完一个文件夹后,将该文件夹从栈中弹出。
下面是C++程序示例:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<direct.h>
#include<io.h>
#include<stack>
using namespace std;
void NonRecursiveTraverseFolder(const char*);
int main()
{
NonRecursiveTraverseFolder("C:\\Users\\Desktop\\test");
return 0;
}
void NonRecursiveTraverseFolder(const char* folderPath)
{
_finddata_t file;
stack<string> folderStack;
string path;
intptr_t handle;
folderStack.push(folderPath);
while (!folderStack.empty())
{
path = folderStack.top();
folderStack.pop();
// 匹配所有文件和文件夹
handle = _findfirst((path + "\\*.*").c_str(), &file);
if (handle == -1)
{
cout << "查找文件失败" << endl;
continue;
}
do
{
if (file.attrib & _A_SUBDIR) // 判断是否是文件夹
{
if (strcmp(file.name, ".") != 0 && strcmp(file.name, "..") != 0) // 排除 . 和 ..
{
folderStack.push(path + "\\" + file.name); // 文件夹路径入栈
cout << path + "\\" + file.name << endl; // 对文件夹进行相应操作
}
}
else // 文件
{
cout << path + "\\" + file.name << endl; // 对文件进行相应操作
}
} while (_findnext(handle, &file) == 0);
_findclose(handle);
}
}
这两种实现方式的具体实现方式略有不同,但是都能够实现遍历文件夹的功能。我们可以根据具体需求选择合适的实现方式。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C++非递归遍历磁盘文件和递归遍历磁盘文件的程序示例 - Python技术站