Simulate the Linux command tee in C

后端 未结 3 1719
我在风中等你
我在风中等你 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:01

    Here is some code I wrote about 20 years ago to implement TEE in Windows. I have been using this with various batch files since then. Note the flush command at the end of each line.

    #include 
    #include 
    
    int main (int argc, char * argv[])
    {
        if (argc < 2 )
        {
            printf ("Error:  No output file name given, example:  theCmd 2>&1 |ltee outputFileName \n");
            return 1;
        }
        FILE *Out = _fsopen(argv[argc-1], "a", _SH_DENYWR);
        if (NULL == Out)
        {
            char buf[300];
            sprintf_s(buf, 300, "Error openning %s", argv[argc-1]);
            perror(buf);
            return 1;
        }
        int ch;
        while ( EOF != (ch=getchar()))
        {
            putchar(ch);
            putc(ch, Out);
            if ( '\n' == ch )
                fflush(Out);
        }
        _flushall();
        fclose(Out);
        return 0;
    }
    

提交回复
热议问题