Simulate the Linux command tee in C

后端 未结 3 1677
我在风中等你
我在风中等你 2021-01-21 13:03

I have to do the simulation of the command tee in C for Linux. How does tee work internally? It looks like a T-shaped pipe, so should I use a pipe? Is

3条回答
  •  天涯浪人
    2021-01-21 14:00

    tee takes stdin and copies the data stream to stdout as well as a file given as an option, it can be used in many very different situations.

    An implementation in C is quite simple, just make a program that copies all data from stdin to stdout, but also use the same output statements for stdout on a file that you opened based on the command line argument.

    basically in pseudo code:

    file f = open(argv[1])
    while (! end of file stdin) {
      buffer = read stdin
      write stdout buffer
      write f buffer
    }
    close(f)
    

    Note that you don't really have to do anything with pipes, your shell will sort out the pipes, the program only has to copy data from one stream to two others.

提交回复
热议问题