DEV Community

BC
BC

Posted on

Implement `tee` CLI in C - C Lang

The tee CLI read from stdin, then write date to stdout and the file name specified.

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

int main(int argc, char* argv[]) {
    if (argc != 2) {
        fprintf(stderr, "%s\n", "Output file name required");
        return 1;
    }
    char buffer[1024] = {0};
    int outfd = open(argv[1], O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (outfd == -1) {
        fprintf(stderr, "%s\n", "Failed to create output file");
        return 2;
    }
    ssize_t nread = 0;
    while((nread = read(STDIN_FILENO, buffer, 1024)) != 0) {
        if (write(STDOUT_FILENO, buffer, nread) != nread) {
            fprintf(stderr, "%s\n", "Failed to write to stdout");
            return 3;
        }
        if (write(outfd, buffer, nread) != nread) {
            fprintf(stderr, "%s\n", "Failed to write to file");
            return 4;
        }
    };
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Use gcc to compile and run:

$ gcc main.c -o mytee
Enter fullscreen mode Exit fullscreen mode

Test:

$ date | ./mytee log.txt
Mon 27 Apr 2020 10:20:55 PM EDT
$ cat log.txt 
Mon 27 Apr 2020 10:20:55 PM EDT
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
ac000 profile image
Andrew Clayton

Of course, Linux has a tee(2) system call (and I mean system call, not the tee(1) command...)

Collapse
 
bitecode profile image
BC

nice, I didn't know that, thank you Andrew :D