Skip to content

Instantly share code, notes, and snippets.

@zain-saqer
Last active July 30, 2021 17:26
Show Gist options
  • Save zain-saqer/9153cda88739a5ffc1fec5b7cb84cc67 to your computer and use it in GitHub Desktop.
Save zain-saqer/9153cda88739a5ffc1fec5b7cb84cc67 to your computer and use it in GitHub Desktop.
/**
* This is a simple implementation of the Unix's tee command
* It's a solution for the exercise 4-1 in "The Linux Programming Interface" book
*
* auther: Zain Saqer (github.com/zain-saqer)
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int opt;
char *file = NULL;
char buf[BUFFER_SIZE];
int fd, flags;
opt = getopt(argc, argv, "a");
int append = opt == 'a';
if (append && optind >= argc) {
fprintf(stderr, "Usage: %s [ [ -a ] [ File ] ]\n",
argv[0]);
exit(EXIT_FAILURE);
}
if (optind < argc) {
file = argv[optind];
flags = O_CREAT | O_WRONLY | O_TRUNC;
if (append)
flags = O_CREAT | O_WRONLY | O_APPEND;
if ((fd = open(file, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1) {
perror("open");
exit(EXIT_FAILURE);
}
}
ssize_t n;
while ((n = read(STDIN_FILENO, buf, BUFFER_SIZE)) > 0) {
// write to stdout
ssize_t n2 = 0;
while(n2 != -1 && n2 < n)
n2 = write(STDOUT_FILENO, buf + n2, n - n2);
if (file) {
n2 = 0;
while(n2 != -1 && n2 < n)
n2 = write(fd, buf + n2, n - n2);
if (n2 == -1) {
perror("write to file");
exit(EXIT_FAILURE);
}
}
}
if (file)
close(fd);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment