0

我在这里拉头发。自从我完成任何 c 编程以来已经有 1.5 年了,所以请耐心等待。

我需要在 c 中创建一个函数来完成 pwd 函数在 linux 中的作用。我有一个代表文件夹的节点结构。每个人都有一个指向其父级的指针,所以它应该很容易,但我要死在这里。我想我可以继续使用 strcat 将节点父节点的名称附加到路径名称。但是,即使我能够让它工作,我也会留下一个相反的列表,我想这很好。我至少可以应付。但是,如果我在目录 c 中,其父级为 b,其父级为 a,其父级为 root,我应该能够使用 pwd 输出字符串“/a/b/c”。我被困住了。有任何想法吗?当我尝试使用 strcat 时,我得到了 ying yang 的分段错误。

void pwd( ){  

    char *thePath;
    NODE *nodePtr;
    nodePtr = cwd;

    while( nodePtr != root ){

    }
    printf("%s\n", thePath);
    return;
}   
4

1 回答 1

1

如果您只想打印出路径,那么递归应该很容易。

void pwd_recurse (NODE *nodePtr)
{
    if (nodePtr == root)
    {
         return;
    }
    pwd_recurse(nodePtr->parent);
    printf("/%s",nodePtr->name);
}

void pwd()
{
    ///however you get the nodePtr;
    pwd_recurse(nodePtr);
    printf("\n");
}

This nicely sidesteps having to deal with memory allocations (though it does mean if you have a degenerate filesystem with loops (insert obligatory XKCD cartoon here), you'll have a stackoverflow, which is arguable better than an infinite loop.)

于 2013-01-27T17:08:06.803 回答