目录树

/*
参考文档:
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值