【问题标题】:Implementing a struct that can have parents/children实现一个可以有父母/孩子的结构
【发布时间】:2015-07-23 21:10:03
【问题描述】:

所以我正在尝试实现一个 UNIX 文件系统并且遇到了一些麻烦,因为我以前没有使用过那么多结构。我对编程相当陌生。这就是我现在拥有的:

typedef struct Unix{
    char *name;
    struct Unix *parentDirectory;
    struct Unix **subDirectories;
} FileSystem;

我将它放在一个名为 Unix.c 的单独文件中,该文件通过标题传递到我的 main.c 文件中。 parentDirectory 将是指向父目录的指针,而 subDirectories 将是指向所有子目录的指针。

我的问题是如何访问主文件中的目录和子目录。我的另一个问题如下:假设我创建了以下内容:/home/TestUser/Desktop/StephCurry/WithTheShot。如果我删除目录 StephCurry,我将如何更改该目录上方的所有其他父/子目录结构?我相信这与数据结构有关,但我不是 100% 确定。

谢谢各位。我真的很喜欢编程,这很有趣!我只是在实现这些东西时遇到了一些麻烦。

【问题讨论】:

  • 如果您是编程新手,为什么要实现UNIX filesystem
  • 不要走错路,但如果你刚刚开始学习 C 和编程,编写自己的文件系统可能会有点牵强。也许从一些更小、更集中的练习开始?
  • 您是否要在文件系统的内存模型中制作?

标签: c


【解决方案1】:

我的问题是如何访问目录和子目录 在我的主文件中。

// example: print given directory and all subdirectories recursively
void prdirr(FileSystem *dir)
{
    puts(dir->name);
    FileSystem **subdirp = dir->subDirectories;
    if (subdirp)
        for (; *subdirp; ++subdirp)
            prdirr(*subdirp);
}
...
    FileSystem root = { "", NULL, calloc(1, sizeof (FileSystem *)) };
    ...
    prdirr(&root);

我的另一个问题是:假设我有 以下创建:/home/TestUser/Desktop/StephCurry/WithTheShot。如果我 删除目录 StephCurry,我将如何更改所有其他目录 该目录上方的父/子目录结构?

您不必更改所有其他父/子目录结构 - 您只需从其父 DesktopsubDirectories 中删除目录 StephCurry(和 @ 987654326@ 删除的结构,如果它们已经被malloced,当然)。假设dir指向节点StephCurry

// free memory of given directory and all subdirectories recursively
void dedirr(FileSystem *dir)
{
    FileSystem **subdirp = dir->subDirectories;
    if (subdirp)
        for (; *subdirp; ++subdirp)
            dedirr(*subdirp), free(*subdirp);   // free the node
    free(dir->subDirectories);  // free the list
}
...
    // remove dir from parent's list of subDirectories
    if (dir->parentDirectory)   // won't remove root
    {
        FileSystem **subl, **subr;
        subl = subr = dir->parentDirectory->subDirectories;
        do if (*subr == dir) ++subr; while (*subl++ = *subr++);
        dedirr(dir);    // free memory of deleted dir tree
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多