-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsum.cpp
More file actions
53 lines (46 loc) · 1.65 KB
/
sum.cpp
File metadata and controls
53 lines (46 loc) · 1.65 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
#include <cstdio>
#include <string>
#include <cfbox/args.hpp>
#include <cfbox/checksum.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "sum",
.version = CFBOX_VERSION_STRING,
.one_line = "checksum and count the blocks in a file",
.usage = "sum [-s] [FILE]...",
.options = " -s use System V sum algorithm (512-byte blocks)",
.extra = "",
};
} // namespace
auto sum_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'s', 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 sysv = parsed.has('s');
const auto& pos = parsed.positional();
auto paths = pos.empty() ? std::vector<std::string_view>{"-"} : pos;
int rc = 0;
for (auto p : paths) {
auto data_result = (p == "-") ? cfbox::io::read_all_stdin() : cfbox::io::read_all(p);
if (!data_result) {
CFBOX_ERR("sum", "%s", data_result.error().msg.c_str());
rc = 1;
continue;
}
if (sysv) {
auto result = cfbox::checksum::sysv_sum(*data_result);
std::printf("%u %u", result.checksum, result.blocks);
} else {
auto result = cfbox::checksum::bsd_sum(*data_result);
std::printf("%05u %5u", result.checksum, result.blocks);
}
if (p != "-") std::printf(" %.*s", static_cast<int>(p.size()), p.data());
std::putchar('\n');
}
return rc;
}