我对C编程很陌生,所以请耐心等待我。下面是我的C语言代码。根据我的知识应该工作,但当我进入“退出”然后根据我的逻辑它应该工作。它不是。好吧,让我知道我做错了什么。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int main () {
char command[50];
do{
int pid ;
char bin_dir[100] ;
char sbin_dir[100] ;
command[50] = '\0';
printf("\n get input to execute command: ");
fgets (command, 100, stdin);
printf("\n Entered command is : %s " ,command);
strcpy(sbin_dir,"/sbin/");
strcpy(bin_dir,"/bin/");
strcat(bin_dir ,command);
strcat(sbin_dir ,command);
if( access( bin_dir, F_OK ) != -1 ) {
printf(" command found in bin Directory \n");
} else if (access( sbin_dir, F_OK ) != -1 ) {
printf(" command found in sbin Directory \n");
}else {
printf("command not found \n");
}
}while(strcmp (command, "exit") == 0);
return 0;
}
答案 0 :(得分:4)
while (strcmp(...) != 0)
,而不是== 0
。fgets
会在最后读取LF行 - 比较strcmp(command,"exit\n")
。 PS:command[50] = '\0'
错了。必须为command[49] = 0
或更高memset(command, 0, sizeof command)
。
PS2:fgets (command, 100, stdin)
几乎没有问题 - command
是50个字节的数组,fgets
最多允许100个。使用fgets (command, sizeof command, stdin)
。