如何遍历某一目录下的子目录和文件并将遍历的结果保存在一个孩子兄弟树中?
各位帮忙看看 如何实现 :如何遍历某一目录下的各级子目录和文件并将遍历的结果保存在一个孩子兄弟树中?遍历完后要将目录的层次结构信息存储到孩子兄弟树中。
[解决办法]
胡乱写个你参考
#include "windows.h"#include "iostream"#include "string"using namespace std;struct Node { string strName; Node* pChild; Node* pSlibing; Node(string Name, Node* child, Node* slibing) { strName = Name; pChild = child; pSlibing = slibing; } Node() { strName = TEXT(""); pChild = NULL; pSlibing = NULL; }};Node* BuildDirTree(string strDir) { WIN32_FIND_DATA FindData; HANDLE Handle = FindFirstFile(strDir.c_str(), &FindData); strDir.resize(strDir.size() - 1); Node* pRoot = new Node(strDir, NULL, NULL); Node* pRrev = NULL; while (FindNextFile(Handle, &FindData)) { if (string(FindData.cFileName) == TEXT("..")) continue; if (string(FindData.cFileName) == TEXT(".")) continue; if (FindData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) { string strTemp = strDir; strTemp += string(FindData.cFileName); strTemp += TEXT("\\*"); Node* pTemp = BuildDirTree(strTemp); if (!pRoot->pChild) pRoot->pChild = pTemp; else pRrev->pSlibing = pTemp; pRrev = pTemp; } } return pRoot;}int main() { Node* pRoot = BuildDirTree(TEXT("E:\\*")); // delete tree return 0;}
[解决办法]
多叉树?
这个其实没什么大的区别,
1 看看多叉树的建立
2 寻找目录遍历代码
然后把遍历获得的文件/目录名作为多叉树建立的数据就可以了
Dev C++ 测试通过:利用链表实现目录内所有文件列表显示
#include <stdio.h>
#include <dirent.h>
/*#include <alloc.h>*/
#include <string.h>
void main(int argc,char *argv[])
{
DIR *directory_pointer;
struct dirent *entry;
struct FileList
{
char filename[64];
struct FileList *next;
}start,*node;
if (argc!=2)
{
printf("Must specify a directory\n");
exit(1);
}
if ((directory_pointer=opendir(argv[1]))==NULL)
printf("Error opening %s\n",argv[1]);
else
{
start.next=NULL;
node=&start;
while ((entry=readdir(directory_pointer))!=NULL)
{
node->next=(struct FileList *)malloc(sizeof(struct FileList));
node=node->next;
strcpy(node->filename,entry->d_name);
node->next=NULL;
}
closedir(directory_pointer);
node=start.next;
while(node)
{
printf("%s\n",node->filename);
node=node->next;
}
}
}
[解决办法]
递归就可以了.
编译器用 release 时,编译器会判断得出你是用递归算法, 并给你提供优化, 优化出来的结果, 可能比你自己手工写不用递归还要快,占用资源还要少.
实际上, 从 vc2.0 时代开始, 世界上的c语言编译器就已经很聪明了.