思路很简单,从标准输入文件描述符读入数据,然后同时向标准输出和参数指定的文件写出数据;如果加了 -a 选项,则以追加的方式向文件写出数据。还没了解 getopt() 函数就没判断参数是否合法。

Linux/UNIX编程:实现简单 tee 命令-LMLPHP

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h> #ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif int main(int argc, char const *argv[])
{
int outputFd;
/* 命令格式要求为 `tee [-a] file`,没有判断参数是否合法*/
if(argc == 3){ //加了 -a 选项,则以追加的方式写数据
outputFd = open(argv[2], O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR | S_IRGRP); //rw-r-----
} else if (argc == 2){
outputFd = open(argv[1], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP); //rw-r-----
} if(outputFd == -1){
perror(strerror(errno));
exit(EXIT_FAILURE);
} char buffer[BUF_SIZE];
int readNum; while((readNum = read(STDIN_FILENO, buffer, BUF_SIZE)) > 0){
ssize_t fileWrNum = write(outputFd, buffer, readNum); //向指定文件写出数据
ssize_t stdoutWrNum = write(STDOUT_FILENO, buffer, readNum); //向标准输出写入数据 if(fileWrNum != readNum || stdoutWrNum != readNum){ //判断是否写成功
perror("couldn't write the whole buffer\n");
exit(EXIT_FAILURE);
}
}
if(readNum == -1){ //判断是否读取成功
perror(strerror(errno));
exit(EXIT_FAILURE);
} if(close(outputFd) == -1){ //判断是否成功关闭
perror(strerror(errno));
exit(EXIT_FAILURE);
}
   exit(EXIT_SUCCESS);
}

  

05-27 04:19