简体   繁体   English

在C中制作pwd类型的函数

[英]make a pwd type function in c

I'm pulling my hair out here. 我在这里拔头发。 Its been about 1.5 years since I've done any c programming so bear with me. 自从我完成任何c编程以来已经有1.5年了,请耐心等待。

I need to make a function in c that does what the pwd function does in linux. 我需要在c中创建一个函数,该函数执行linux中pwd函数的作用。 I have a struct of nodes that represent a folder. 我有一个代表文件夹的节点结构。 Each one has a pointer back to its parent so it should be pretty easy but I'm dying here. 每个人都有一个指向其父对象的指针,因此应该很简单,但我死在这里。 I thought I could just keep using strcat to append the name of a nodes parent to the path name. 我以为我可以继续使用strcat将父节点的名称附加到路径名。 But, even if I was able to get this to work I would be left with a list that is in reverse, which is fine I guess. 但是,即使我能够做到这一点,我也会留下一个相反的列表,我想这很好。 I could at least deal with that. 我至少可以处理。 But if I'm in directory c whose parent is b whose parent is a whose parent is root I should be able to use pwd to output the string "/a/b/c". 但是,如果我在父目录为b的目录c中,其父目录是其父目录是root的目录c,则应该能够使用pwd输出字符串“ / a / b / c”。 I'm stuck. 我被卡住了。 Any ideas? 有任何想法吗? When I try to use strcat I get segmentation faults up the ying yang. 当我尝试使用strcat时,出现了分割错误。

void pwd( ){  

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

    while( nodePtr != root ){

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

If all you want to do is print out the path, this should be pretty easy with recursion. 如果您只想打印出路径,那么使用递归应该很容易。

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.) 这很好地回避了必须处理的内存分配问题(尽管这确实意味着如果您的循环系统具有退化的文件系统(在此处插入强制性的XKCD卡通),则会产生stackoverflow,这比无限循环要好得多。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM