在文章“简单tee.c的实现”中这里写链接内容,会出现空等待的问题,我在学习的过程中修改了该代码,以备今后的学习。
对代码的分析要点:
使用getopt()来解析命令行参数,多种编程语言都有实现,需要学习
open()打开标准输入时使用了文件描述符STDIN_FILENO-标准输入,其他文件描述符如STDOUT_FILENO-标准输出,STDERR_FILENO-标准错误
代码
/**
The tee command reads its standard input until end-of-file, writing a copy of the input
to standard output and to the file named in its command-line argument. Use getopt() to anaylsis
the command.
*/
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#ifndef BUF_SIZE
#define BUF_SIZE 1024
#endif
static void print_usage(void) {
puts("usage:\n-a append to the file\n-h or -? help\ndefault:write a new file or overwrite the file\n");
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
int flag_append = 0;
const char *file_name;
int opt;
if ((opt = getopt(argc, argv, "ah?")) != -1) {
switch(opt) {
case 'a':
flag_append = 1;
break;
case 'h':
case '?':
print_usage();
}
}
if (optind >= argc) {
exit(EXIT_FAILURE);
}
file_name = argv[optind];
ssize_t num_read;
char buf[BUF_SIZE];
int flag = O_WRONLY | O_CREAT;
if (flag_append) {
flag |= O_APPEND;
} else {
flag |= O_TRUNC;
}
int fd = open(file_name,
flag,
S_IRUSR | S_IWUSR | S_IRGRP
| S_IWGRP | S_IROTH | S_IWOTH );
if (fd == -1) {
exit(EXIT_FAILURE);
}
while ((num_read = read(STDIN_FILENO, buf, BUF_SIZE)) > 0) {
write(fd, buf, num_read);
}
if (num_read == -1) {
exit(EXIT_FAILURE);
}
if (close(fd) == -1) {
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}