C:如何检查用户的空输入

C:如何检查用户的空输入,c,null,user-input,C,Null,User Input,我正在构建一个可遍历的目录树 这是我的“cd”shell命令代码 cd directoryName-返回具有directoryName的目录 返回根目录 cd..-返回当前目录的父目录 如何检查返回根目录时的空用户输入 if (strcmp(arg, "") == 0) { return root; } 当您按“cd”时,似乎抛出了一个分段错误 // *checks whether cwd has a subdirectory named arg // *if yes, the fun

我正在构建一个可遍历的目录树

这是我的“cd”shell命令代码

cd directoryName-返回具有directoryName的目录

返回根目录

cd..-返回当前目录的父目录

如何检查返回根目录时的空用户输入

if (strcmp(arg, "") == 0) {
    return root;
}
当您按“cd”时,似乎抛出了一个分段错误

// *checks whether cwd has a subdirectory named arg
// *if yes, the function returns the corresponding tree node (and become new working directory)
// *if no, prints an error message
// *handle cd and cd ..
struct tree_node *do_cd(struct tree_node *cwd, struct tree_node *root, char *arg) {

    // initialising subDir to cwd's first child
    struct list_node *subDir = cwd -> first_child;

    // initialising parDir to cwd's parent
    struct tree_node *parDir = cwd -> parent;

    if (parDir != NULL) {
        if (strcmp(arg, "..") == 0) {
            cwd = parDir;
            printf("Returning to parent directory.\n");
            return cwd;
        }
    }

    if (strcmp(arg, ".") == 0) {
        return cwd;
    }

    if (strcmp(arg, "") == 0) {
        return root;
    }

    // checks if cwd has a subdirectory named arg
    while (subDir != NULL) {
        if (strcmp(subDir -> tree -> string_buffer, arg) == 0) {
            printf("Subdirectory exists: Entering!\n");
            cwd = subDir-> tree;
            printf("Making subdirectory current working directory: name = %s\n", arg);
            printf("Returning current working directory: %s.\n", arg);
            return cwd;
        }
        //else if (strcmp(arg, "") == 0) {
        //    printf("Returning to root directory.\n");
        //    return root;
        //}
        subDir = subDir-> next;
    }

    printf("Directory does not exist!\n");
    return cwd;
}

我猜您的
do_cd
函数是通过
NULL
arg参数调用的,因此使用
SIGSEGV
。对此进行检查可以实现以下目的:

if (arg == NULL || !strcmp(arg, ""))
   return root;

我不知道您的解析器的实现,但我可以猜测它(可能)永远不会使用arg的空字符串(
“”
)调用
do\u cd
函数。

我猜您的
do\u cd
函数会使用
NULL
arg参数调用,因此使用
SIGSEGV
。对此进行检查可以实现以下目的:

if (arg == NULL || !strcmp(arg, ""))
   return root;

我不知道您的解析器的实现,但我可以猜到它(可能)永远不会使用arg的空字符串(
“”
)调用您的
do\u cd
函数;不工作我不认为我空终止了我的arg输入,我可能会这样做。是否只是将\0添加到结尾?是的,strcmp需要以NULL结尾的字符串。知道字符串长度通常是一种很好的做法,因此可以使用strncmp而不是strcmp。如果你知道长度,你可以做arg[len]=0;len++;我认为我的参数是strep(字符串分隔的),所以它是这样的:mkdir_hello,argument=hello,它不会单独处理'mkdir',因为mkdir_uu将是arg=”“Great的情况。这通常是一个很好的实践,所以说你做了什么来解决问题。如果(arg==NULL | | |!strcmp(arg,“”)返回root;不工作我不认为我空终止了我的arg输入,我可能会这样做。是否只是将\0添加到结尾?是的,strcmp需要以NULL结尾的字符串。知道字符串长度通常是一种很好的做法,因此可以使用strncmp而不是strcmp。如果你知道长度,你可以做arg[len]=0;len++;我认为我的参数是strep(字符串分隔的),所以它是这样的:mkdir_hello,argument=hello,它不会单独处理'mkdir',因为mkdir_uu将是arg=”“Great的情况。这通常是一个伟大的实践,所以说你做了什么来解决问题。