-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtee.cpp
More file actions
55 lines (47 loc) · 1.48 KB
/
tee.cpp
File metadata and controls
55 lines (47 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "tee",
.version = CFBOX_VERSION_STRING,
.one_line = "read from stdin and write to stdout and files",
.usage = "tee [-a] [FILE]...",
.options = " -a append to the given FILEs, do not overwrite",
.extra = "",
};
} // namespace
auto tee_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'a', false},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
bool append = parsed.has('a');
const auto& pos = parsed.positional();
std::vector<cfbox::io::unique_file> files;
for (auto p : pos) {
auto* f = std::fopen(std::string{p}.c_str(), append ? "ab" : "wb");
if (!f) {
CFBOX_ERR("tee", "%s: %s", std::string{p}.c_str(), std::strerror(errno));
} else {
files.emplace_back(f);
}
}
char buf[4096];
int rc = 0;
while (auto n = std::fread(buf, 1, sizeof(buf), stdin)) {
std::fwrite(buf, 1, n, stdout);
for (auto& f : files) {
if (std::fwrite(buf, 1, n, f.get()) != n) {
rc = 1;
}
}
}
return rc;
}