我对C语言很陌生,我正在写一些最终会成为shell或至少类似的东西。我有一个 char 变量command
,我有一个 if 语句,当 charcommand
将"cd"作为字符串时cd()
执行(或至少应该)函数。但由于某种原因它不起作用,并且总是执行cd
.
对不起,如果解释是垃圾,但英语不是我的母语,我说得不好。无论如何,这是代码(请忽略 chdir 暂时不做任何事情):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int loop=1;
char command[512];
while (loop == 1) {
FILE *command_file;
command_file = fopen("/tmp/EXECUTE", "w");
printf("SHELL > ");
fgets(command, sizeof(command), stdin);
fprintf(command_file, "%s", command);
if (strcpy(command, "cd")) {
cd();
}
else {
printf("%s", command);
}
fclose(command_file);
execution();
}
}
void execution() {
char r;
FILE *exec_file;
exec_file = fopen("/tmp/EXECUTE", "r");
system("sh /tmp/EXECUTE");
}
void cd() {
char path;
printf("Enter a path: ");
path = getc(stdin);
chdir();
}
抱歉,如果代码有点令人毛骨悚然,但我真的需要帮助!如果你只想要 if 语句:
if (strcpy(command, "cd")) {
cd();
}
else {
printf("%s", command);
}
你的代码有两个问题:
-
fgets
读取并在字符串中包含换行符。因此,如果输入cd
后跟换行符,则fgets
会将"cdn"
放入缓冲区中。删除换行符的一种简单方法是使用
strcspn
函数:command[strcspn(command, "n")] = 0;
-
第二个问题是,当两个字符串匹配时,
strcmp
返回零(即 false)。所以你的比较应该是:if (strcmp(command, "cd") == 0)
哦,正如评论中提到的,您应该使用strcmp
来比较字符串,而不是strcpy
哪个是字符串副本。