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?

2

3 Answers

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"); } 
0

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy