简体   繁体   English

C中的Unix Shell-更改目录

[英]Unix Shell in C - Change Directory

I'm another CS beginner working on a simple Shell. 我是使用简单Shell的另一位CS初学者。 At the moment I am trying to change the current directory if an argument is passed, else, report to the current directory. 目前,如果要传递参数,我将尝试更改当前目录,否则,请报告当前目录。

I tried using chdir() in my program, but it's apparently not working. 我尝试在程序中使用chdir() ,但显然无法正常工作。 I tried passing a char* arguments which is tokenized. 我尝试传递一个已标记化的char*参数。 I also tried with argv[1] , but I must be doing something wrong because neither seems to work. 我也尝试过使用argv[1] ,但是我必须做错了什么,因为两者似乎都不起作用。

Also, I'm not exactly sure how to make the argument pointer (containing the directory string) static, so that when i use putenv(ARGUMENT HERE) there are no issues. 另外,我不确定如何使参数指针(包含目录字符串)静态化,因此当我使用putenv(ARGUMENT HERE)时没有问题。

Here is the pertaining part of my code: 这是我的代码的相关部分:

else if (strncmp(command[0], "cd", 2) == 0)
    {
        char *argmnts = strtok(0, " ");

        if (arguments != NULL)
        {
            chdir(argmnts); 
            putenv(argmnts); // THE ARG STRING NEEDS TO BE A STATIC COPY
            getcwd(promptBuff, sizeof(argmnts));
        }
    }

The pointer argmnts points to the tokenized argument part from: char strnBuffer[1000] which has already been tokenized for the command: command[0] = strtok(strnBuffer, " "); 指针argmnts指向以下char strnBuffer[1000]的标记化参数部分: char strnBuffer[1000] ,该char strnBuffer[1000]已为命令标记化: command[0] = strtok(strnBuffer, " ");

I really appreciate any help/insight. 我非常感谢您的帮助/见解。

Thank you. 谢谢。

You probably have a '\\n' left over on the end of the input line. 您可能在输入行的末尾有一个'\\n' Your strtok only recognizes space as separator, so it won't touch the newline. 您的strtok仅将空格识别为分隔符,因此不会碰到换行符。 chdir("dir\\n") will fail unless you actually have a directory with the newline at the end of its name. chdir("dir\\n")将会失败,除非您实际上有一个目录,其名称末尾带有换行符。

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

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