10079. Tiny Command Tool

I'm a slow walker, but I never walk backwards.

期末無關,請迴避

題目描述

模擬 Linux 環境下的指令。

tct.h

1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef _TCT_H
#define _TCT_H
 
typedef struct Directory {
    char name[256];
    struct Directory *childDir;
    struct Directory *silbingDir;
} Directory;
 
void tree(Directory *fs);
Directory* cd(Directory *fs, char path[]);
 
#endif
  • void tree(Directory *fs);
  • Directory* cd(Directory *fs, char path[]);

main.c (test)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "tct.h"
 
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
 
Directory* mkDir(char name[]) {
    Directory *d = (Directory *) malloc(sizeof(Directory));
    strcpy(d->name, name);
    d->silbingDir = d->childDir = NULL;
    return d;
}
Directory* newDir(char name[], int n, ...) {
    va_list args;
    va_start(args, n);
    Directory *u = mkDir(name), *p = NULL;
    for (int i = 0; i < n; i++) {
        Directory *para = va_arg(args, Directory*);
        if (i == 0)   
            u->childDir = para;
        if (p != NULL)
            p->silbingDir = para;
        p = para;
    }
    va_end(args);
    return u;
}
int main() {
    Directory *fs =
        newDir("root", 3,
            newDir("home", 2,
                newDir("morris", 1,
                    newDir("workspace", 0)),
                newDir("stephanie", 0))
            , newDir("etc", 0)
            , newDir("bin", 2
                , newDir("arch", 0)
                , newDir("cat", 0))
        );
    tree(fs);
 
    char path[128] = "home/morris";
    tree(cd(fs, path));
    tree(fs);
    return 0;
}

Sample Output

+- root
   |
   +- home
   |  |
   |  +- morris
   |  |  |
   |  |  +- workspace
   |  |
   |  +- stephanie
   |
   +- etc
   |
   +- bin
      |
      +- arch
      |
      +- cat
+- morris
   |
   +- workspace

Discussion