POJ1057 FILE MAPPING 恶心模拟

题意:介绍一种控制台下的文件目录输出格式,要求进行模拟.详见代码

代码如下:

#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

/*
    目测应该要抽象出文件和目录这两个结构
    对于文件我们可以有一个很清醒的认识,也就是说所
    有的文件总是离不开目录存在,同一目录下,文件按
    照字典序来排列且文件总是放在所有子目录的下面 
    而目录则严格按照出现的先后顺序来排列
    
    文件先用一个栈来保存,每次记录深度和文件名称 
*/

struct File {
    int deep;
    string name;    
}info;

stack<File>stk;
vector<string>v;

void display(int deep) {
    v.clear();
    while (!stk.empty()) {
        if (stk.top().deep == deep) {
            string str = stk.top().name;
            v.push_back(str);
            stk.pop();
        } else {
            break;    
        }
    } 
    sort(v.begin(), v.end());
    for (vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
        for (int i = 0; i < deep; ++i) {
            printf("|     ");
        }
        cout << *it << endl;
    }
}

int main() {
//    freopen("1.in", "r", stdin);
//    freopen("1.out", "w", stdout);
    char op[200];
    int ca = 0, start = 1, first = 1, deep = 0;
    // deep 用来标记目录的层次 
    while (scanf("%s", op), op[0] != '#') {
        // '#'为结束 标记符号 
        if (start) {
            if (!first) puts("");
            printf("DATA SET %d:\nROOT\n", ++ca);
            first = start = 0;
        }
        if (op[0] == '*') { 
            start = 1;     
            display(deep);
        } else if (op[0] == 'f') {
            info.deep = deep;
            info.name = string(op); // 获得当前这个文件的信息 
            stk.push(info); // 将这个文件压栈 
        } else if (op[0] == 'd') {
            ++deep;
            for (int i = 0; i < deep; ++i) {
                printf("|     ");
            } // 对于子目录,直接输出
            printf("%s\n", op);
        } else {
            display(deep);
            --deep;
        }
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/Lyush/p/2846824.html