非递归方式遍历文件夹,取得所有子目录和文件的文件名和大小
void BuildTree() { FileNode nodeD; nodeD.fileName = _T("D"); nodeD.fileSize = 15; FileNode nodeE; nodeE.fileName = _T("E"); nodeE.fileSize = 10; FileNode nodeF; nodeF.fileName = _T("F"); nodeF.fileSize = 20; FileNode nodeG; nodeG.fileName = _T("G"); nodeG.fileSize = 5; FileNode nodeB; nodeB.fileName = _T("B"); nodeB.fileSize = 0; nodeB.subFiles.push_back(nodeD); nodeB.subFiles.push_back(nodeE); FileNode nodeC; nodeC.fileName = _T("C"); nodeC.fileSize = 0; nodeC.subFiles.push_back(nodeF); nodeC.subFiles.push_back(nodeG); FileNode nodeA; nodeA.fileName = _T("A"); nodeA.fileSize = 0; nodeA.subFiles.push_back(nodeB); nodeA.subFiles.push_back(nodeC); list<pair<FileNode*, FileNode*> > findFolder; findFolder.push_back(make_pair(&nodeA, (FileNode*)NULL)); FileNode* preNode = NULL; list<FileNode>::iterator pos; while (!findFolder.empty()) { FileNode* node = findFolder.back().first; FileNode* parent = findFolder.back().second; if (!node->subFiles.empty() && &(*(node->subFiles.begin())) != preNode) { for (pos = node->subFiles.begin(); pos != node->subFiles.end(); ++pos) { findFolder.push_back(make_pair(&(*pos), node)); } } else { // 访问该节点 if (parent) { parent->fileSize += node->fileSize; } preNode = node; findFolder.pop_back(); } } }