/*
参考文档:
https://blog.csdn.net/qq_35440678/article/details/80147601
https://blog.csdn.net/qq_42623428/java/article/details/82961479
*/
#include <iostream>
#include <string>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
struct File
{
char name[300];
//定义 长度
};
struct node
{
int node_len=0;
int file_len=0;
char name[300];
node *node_next[300];
File *file_next[300];
};
int Nodecmp(node* a,node* b)//目录字典序排序
{
return strcmp(a->name,b->name)<0;
}
int Filecmp(File* a,File* b)//文件字典序排序
{
return strcmp(a->name,b->name)<0;
}
void make_tree(char *s, struct node *p)
{
char str[300];
struct node *a;
int len = strlen(s);
int flag = 0;
int i;
for (i = 0; i < len; i++)
{
if (s[i] == '\\')
{
break;
}
}
if (s[i] == '\\')
{
// 如果是目录
strncpy(str, s, i);
str[i] = '\0'; //结束标志要有
// 将i之前的string赋值给str
for (int j = 0; j < p->node_len; j++)
{
if (strcmp(p->node_next[j]->name, str) == 0)
{
flag = 1;
a = p->node_next[j];
break;
}
}
if (flag == 0)
{
strcpy(a->name, str);
//不存在
a = new struct node;
a->node_len = 0;
a->file_len = 0;
p->node_next[p->node_len++] = a;
}
if (i < len - 1)
make_tree(s + i + 1, a);
else
{
return;
}
} // 如果是目录
else
{
File *b = new File;
strcpy(b->name, s);
p->file_next[p->file_len++] = b;
} //如果不是的话
}
void print_tree(struct node *p, int n)
{
for (int i = 0; i < n; i++)
{
cout << " ";
}
n++;
//必须要有因为是 endl
cout << p->name << endl;
//输出
sort(p->node_next,p->node_next+p->node_len,Nodecmp);//排序
for(int i=0;i<p->node_len;i++)print_tree(p->node_next[i],n);//递归调用,依次输出文件和目录
sort(p->file_next,p->file_next+p->file_len,Filecmp);//排序
for(int i=0;i<p->file_len;i++){
for(int j=0;j<n;j++)cout<<" "; // 可以将n理解为深度
cout<<p->file_next[i]->name<<endl;//输出文件
}
return;
}
int main()
{
int n;
cin>>n;
node* root= new struct node;
strcpy(root->name,"root");
for(int i=0;i<n;i++){
char s[300];
cin>>s;
make_tree(s,root);
}
print_tree(root,0);
return 0;
}
/*
感觉这个难点在与麻烦 ,需要区分目录还是文件 另外在string结束时候不能忘记'\0'操作符号 ,使用的是strncpy(),(也是用了strcmp,strcpy).
*/
参考文档: (含有sort 的用法)
https://blog.csdn.net/qq_35440678/article/details/80147601
https://blog.csdn.net/qq_42623428/java/article/details/82961479