这次我们实现一个假的cat
命令。
因为是假的,所以不管参数。只要输入
cat README.md
能输出一些内容就行。并没有打开文件这种操作。
下面是代码:
#include <stdio.h>
#include <string.h>
int print_logo(){
printf("%s\n","");
printf("%s\n"," __ _ _ _");
printf("%s\n"," / _| __ _| | _____| (_)_ __ _ ___ __");
printf("%s\n","| |_ / _` | |/ / _ \\ | | '_ \\| | | \\ \\/ /");
printf("%s\n","| _| (_| | < __/ | | | | | |_| |> <");
printf("%s\n","|_| \\__,_|_|\\_\\___|_|_|_| |_|\\__,_/_/\\_\\");
printf("%s\n","");
}
int main(){
print_logo();
char cmd[100];
while(1){
printf("\n%s ","#");
scanf("%s",cmd);
if(strcmp(cmd,"ls")==0){
printf("%s","README.md");
}else if(strcmp(cmd,"cat README.md")==0){
printf("%s\n","## FakeLinux");
printf("%s\n","> a fake linux");
printf("%s","http://github.com/fakelinux");
}else{
printf("Command '%s' not found",cmd);
}
}
return 0;
}
运行效果:
怎么回事儿?一条带有参数的命令cat README.md
怎么被空格拆成2条命令了?
原来,scanf
函数遇到空格就读取一次,所以一个字符串里有空格就会被分成2次输入。现在把 scanf
改成 gets
就可以解决空格的问题:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int print_logo(){
printf("%s\n","");
printf("%s\n"," __ _ _ _");
printf("%s\n"," / _| __ _| | _____| (_)_ __ _ ___ __");
printf("%s\n","| |_ / _` | |/ / _ \\ | | '_ \\| | | \\ \\/ /");
printf("%s\n","| _| (_| | < __/ | | | | | |_| |> <");
printf("%s\n","|_| \\__,_|_|\\_\\___|_|_|_| |_|\\__,_/_/\\_\\");
printf("%s\n","");
}
int main(){
print_logo();
char cmd[100];
while(1){
printf("\r\n%s ","#");
gets(cmd);
if(strcmp(cmd,"")==0){
printf("%s","#");
}else if(strcmp(cmd,"ls")==0){
printf("%s","README.md");
}else if(strcmp(cmd,"cat README.md")==0){
printf("%s\n","## FakeLinux");
printf("%s\n","> a fake linux");
printf("%s","http://github.com/fakelinux");
}else{
printf("Command '%s' not found",cmd);
}
}
return 0;
}
缺点是编译时会产生一个可以忽略的警告:
gcc -o fakelinux main.c
main.c: In function ‘main’:
main.c:20:9: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
20 | gets(cmd);
| ^~~~
| fgets
/usr/bin/ld: /tmp/ccOAlP8X.o: in function `main':
main.c:(.text+0xc4): warning: the `gets' function is dangerous and should not be used.
运行效果: