Simulate the Linux command tee in C

末鹿安然 提交于 2020-11-29 10:11:38

问题


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 there a special kind of pipe?


回答1:


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.




回答2:


I finished the program!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main(int argc, char *argv[]){

FILE *fp, *fp1;
char buffer;

if(argc != 4){
    printf("\nError");
    printf("\nSintaxis: tee [archivo1] [archivo2]\n");
    exit(0);
}

if(strcmp(argv[1], "tee") == 0){
    fp = fopen(argv[2], "r");
    fp1 = fopen(argv[3], "w");

    printf("\Content in %s:\n", argv[2]);

    while(!feof(fp)){
        buffer = fgetc(fp);
        fputc(buffer, fp1);
        printf("%c", buffer);
    }

    printf("\n\n%s received %s\n", argv[3], argv[2]);   

    fclose(fp);
    fclose(fp1);
    }
    else
        printf("\nThe first argument have to be tee\n");
}



回答3:


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 <stdio.h>
#include <share.h>

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;
}


来源:https://stackoverflow.com/questions/12398947/simulate-the-linux-command-tee-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!