我如何获得我的cd函数正确解析空格?

问题描述 投票:0回答:1

我正在用C语言编写UNIX shell。在尝试创建自己的cd函数时,它可以正常工作,但是我无法访问其中包含空格的目录。

我已经尝试像在bash或其他unix shell中一样将参数输入cd来访问带空格的目录,但是它不起作用:

>>> cd some\ directory\ with\ spaces
>>> cd "some directory with spaces"

这里是cd功能的代码:

if (command[1] == NULL) {
    chdir(getenv("HOME"));
    }
else
    if (chdir(command[1]) == -1) {
            printf("%s: no such directory\n", command[1]);
        }

返回以下错误:

some: no duch directory

您可以看到,只有第一个单词被解析为参数/目录名称。

如何获得程序以正确解析空格并使用空格访问目录?

c shell unix cd
1个回答
-2
投票

嗨,我认为您的问题出在其他地方。您可以将目录更改为目录,但是当程序退出时,您将返回到运行程序的主目录。无论如何都是示例代码。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
        char buf[100] = {0};

        if (2 != argc) {
                printf("Error: Program need argument.\n");
                exit(EXIT_FAILURE);
        }

        if(-1 == chdir(argv[1])) {
                printf("ERR: No such file or directory\n");
                exit(EXIT_FAILURE);
        }

        getcwd(buf, 100);
        printf("current working dir: %s\n", buf);

        exit(EXIT_SUCCESS);
}
arash [~]:
>> ./test Test\ Dir/
current working dir: /home/arash/Test Dir
© www.soinside.com 2019 - 2024. All rights reserved.