自己写一个命令,将linux下的常用命令cat echo ls 汇集在这一个命令中

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>

void catfile(int fd)
{
    while(1)
    {
        char buf[1024]={};
        if(!read(fd,buf,sizeof(buf)))
            break;
        printf("%s",buf);
    }
}

void catdir(DIR* dir)
{
    struct dirent* ent=NULL;
    while(ent=readdir(dir))
    {
        printf("%d\t%s\n",ent->d_type,ent->d_name);
    }
}

void catecho(char* str)
{
    printf("%s\n",str);
}

int main(int argc,char* argv[])
{
    if(argc<2)
    {
        perror("too few arguments");
        exit(-1);
    }
    int i=0;
    for(i=1;i<argc;i++)
    {
        DIR* dir=opendir(argv[i]);
        if(dir)
            catdir(dir);
        else
        {
            int fd = open(argv[i],O_RDONLY);
            if(fd==-1)
                catecho(argv[i]);
            else
                catfile(fd);
        }
            
    }

}

 然后编译生成可执行文件,取名为mycat  ,存放在系统默认文件夹或自己配一下环境变量(.bashrc),就可以和bash命令一样使用了

posted on 2013-08-03 16:49  编世界  阅读(515)  评论(0编辑  收藏  举报