C:如何检查用户空输入



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

这是我的"cd"外壳命令的代码。

cd 目录名称 - 返回目录名称的目录

cd - 返回根目录

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

如何检查用于返回根目录的 NULL 用户输入?

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 = %sn", 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;

我不知道你的解析器的实现,但我可以猜测它(可能)永远不会用空字符串( "" ) 调用你的 do_cd 函数用于 arg。

相关内容

  • 没有找到相关文章

最新更新