概述
目录结构如下:
dir*: 表示目录
file*: 表示文件
字符’t’的个数: 表示层级
文件名:dir_struct(需要与程序处于同一级目录下)
dir1
dir1
dir1
file1
file2
dir2
file1
file2
dir3
file1
dir4
dir1
dir1
dir1
dir1
file1
file1
file2
file3
dir2
dir1
file1
dir2
file1
file2
file3
file4
dir3
file1
file2
file3
file1
file1
file2
file3
代码如下:
#include <io.h>
#include <stdio.h>
#include <assert.h>
// #include <direct.h> // vs 下使用
struct FileNode {
char name[255];
FileNode *pParent;
FileNode *pChild;
FileNode *pNextBrother;
};
void DestroyDirStruct(FileNode *node) {
if (node == nullptr) return;
DestroyDirStruct(node->pChild);
DestroyDirStruct(node->pNextBrother);
delete node;
}
int main() {
char *filename = "dir_struct";
FileNode * DirStruct = nullptr;
FileNode * pCurNode = nullptr;
char name[255];
int level;
int cur_level;
int old = _dup(0);
freopen(filename, "r", stdin);
while (gets(name) != nullptr) {
char *pch = name;
while (*pch == 't') ++pch;
cur_level = pch-name;
FileNode *node = new FileNode;
memset(node, 0, sizeof(FileNode));
strcpy(node->name, pch);
if (cur_level == 0) {
DirStruct = node;
}
else {
if (cur_level - level == 1) {
pCurNode->pChild = node;
node->pParent = pCurNode;
}
else if (cur_level - level == 0) {
pCurNode->pNextBrother = node;
node->pParent = pCurNode->pParent;
}
else if (cur_level - level < 0) {
for (int i=level-cur_level; i>0; --i)
pCurNode = pCurNode->pParent;
pCurNode->pNextBrother = node;
node->pParent = pCurNode->pParent;
}
else {
assert(false);
}
}
pCurNode = node;
level = cur_level;
}
fclose(stdin);
_dup2(old, 0);
pCurNode = DirStruct;
while (pCurNode) {
if (strstr(pCurNode->name, "dir") != '