【发布时间】:2018-01-31 16:18:08
【问题描述】:
我应该使用 '-a' 标志选项来实现 Unix 'tee' 命令,该选项会将输入附加到 EOF 而不是覆盖它。问题是我只能将 C 系统调用用于 I/O。到目前为止,我已经能够实现除多个输出之外的所有内容。
在我的 while 循环中,我有两条不同的行,一条写入文件,另一条写入标准输出。如果我将其中一个注释掉,或者将一个放在另一个之前,那是可行的,但同时保留两个则不行。只有我首先调用的 write 函数才能工作。我假设是因为如果我理解正确,它会清空缓冲区。
如何将我输入到标准输入的任何内容写入标准输出和文件?
#include "csapp.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
int aflag = 0;
int n_char = 0;
int c,fd;
char *path;
char buf;
opterr = 0;
// getopt is looking for flags with dashes
while((c = getopt(argc, argv, "a")) != -1)
switch (c)
{
// assign the aflag value to 1, so we know that arg was applied
case 'a':
aflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf(stderr, "Unknown option \\x%x'.\n",optopt);
return 1;
default:
abort();
}
// if the -a flag was provided, we must append, if not overwrite the file
// by default if the file exists.
if(aflag == 1) {
path = argv[2];
fd = open(path,O_WRONLY|O_APPEND,0);
} else {
path = argv[1];
fd = open(path,O_WRONLY,0);
}
// While not EOF, right to stdout and file
while((n_char=read(STDIN_FILENO, &buf,1)) != 0)
n_char=write(fd, &buf, 1);
write(STDOUT_FILENO,&buf,1);
close(fd);
return 0;
}
【问题讨论】:
-
在你的while循环中添加
{}并将write都放入其中。如果没有{},while循环只会执行第一个write。 -
谢谢你的朋友,成功了!
标签: c io buffer system-calls tee