我正在构建一个可遍历的目录树。
这是我的“cd”shell 命令代码。
cd directoryName - 返回带有 directoryName 的目录
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 = %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;
我不知道你的解析器的实现,但我可以猜测它(可能)永远不会用空字符串(“”
)调用你的do_cd
函数精氨酸。
关于C: 如何检查用户 NULL 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258364/