Write a simple cat command

1. This article implements two basic functions of the cat command

     cat FilePath1 FilePath2...: output the content of the file to the terminal

    cat   : output the keyboard input to the terminal

 

2. Thinking analysis:

     The above two functions actually complete the redirection of two files,

    cat FilePath1 FilePath2 ...: Redirect the contents of FilePath1 FilePath2 ... to standard output, which is the function of file copy, that is, copy the contents of FilePath1 FilePath2 ... to standard output.

  cat:  Copy the contents of standard input (keyboard) to standard output.

 

3. Code and testing

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define BUFFER_LEN (512)


//文件复制,将src_fd文件中的内容copy到dest_fd文件中
void copy(int src_fd,int dest_fd)
{
    if((src_fd < 0 )||(dest_fd < 0))
    {
        printf("fd error,src_fd:%d,dest_fd:%d\n",src_fd,dest_fd);

        return ;
    }

    char buf[BUFFER_LEN] = {0};
    ssize_t size = 0;

    while((size = read(src_fd,buf,BUFFER_LEN)) > 0)
    {
        if(write(dest_fd,buf,size) <= 0)
        {
            printf("write error\n");
        }
        
    }
    
}


int main(int argc ,char **argv)
{
    if((argc < 1)||(memcmp("cat",argv[0],strlen("cat")) < 0))
    {
        printf("usage: cat xxx xxx\n");

        return -1;
    }

    int std_in = STDIN_FILENO;   //标准输入 0
    int std_out = STDOUT_FILENO; //标准输出 1
    
    int i = 0;

    for(i = 1;i < argc;i ++)
    {
        std_in = open(argv[i],O_RDONLY);
        
        if(std_in < 0)
        {
            printf("%s open error\n",argv[i]);

            continue;
        }

        //将打开文件的内容copy到标准输出中去
        copy(std_in,std_out);
        close(std_in);
    }
    
    //如果只输入了 cat 命令,将标准输入的内容copy到标准输出中去
    if(argc == 1)
        copy(std_in,std_out);
    



    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/114117192