c语言写一个假的linux(4)

这次增加3个假的命令,分别是 pwd、ifconfig 和 date:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.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 if(strcmp(cmd,"ps")==0){
            printf("%s\n","   PID TTY          TIME CMD");
            printf("%s\n","  1263 pts/2    00:00:00 bash");
            printf("%s","  1518 pts/2    00:00:00 ps");
        }else if(strcmp(cmd,"whoami")==0){
            printf("%s","root");
        }else if(strcmp(cmd,"lsusb")==0){
            printf("%s\n","Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub");
            printf("%s","Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub");
        }else if(strcmp(cmd,"pwd")==0){
            printf("%s","/home");
        }else if(strcmp(cmd,"ifconfig")==0){
            printf("%s\n","Command 'ifconfig' not found, but can be installed with:");
            printf("%s","pkg install net-tools");
        }else if(strcmp(cmd,"date")==0){
            time_t t;
            time(&t);
            printf("%s",ctime(&t));
        }else{
            printf("Command '%s' not found",cmd);
        }
    }
    return 0;
}

运行效果
在这里插入图片描述
反正都是假的,pwd 和 ifconfig 非常的敷衍,就是输出字符串:

if(strcmp(cmd,"ifconfig")==0){
     printf("%s\n","Command 'ifconfig' not found, but can be installed with:");
     printf("%s","pkg install net-tools");
}

但是 date 命令其实是真的取了系统时间:

if(strcmp(cmd,"date")==0){
     time_t t;
     time(&t);
     printf("%s",ctime(&t));
}

为什么日期换了一行呢?
原来是ctime函数自带换行符。
所以,要用字符串拷贝的方式,去掉这个换行符。

time_t t;
time(&t);
char *strdate = ctime(&t);
char datestr[100];
strncpy(datestr, strdate, strlen(strdate)-1);  //不拷贝换行
datestr[strlen(strdate)-1] = '\0';
printf("%s",datestr);

编译再看效果,多出来的换行已经没了:

在这里插入图片描述
本例子源代码位于 https://github.com/fakelinux/demo/blob/master/004/main.c

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值