-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomm.cpp
More file actions
79 lines (70 loc) · 2.38 KB
/
comm.cpp
File metadata and controls
79 lines (70 loc) · 2.38 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <cstdio>
#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 = "comm",
.version = CFBOX_VERSION_STRING,
.one_line = "compare two sorted files line by line",
.usage = "comm [-123] FILE1 FILE2",
.options = " -1 suppress column 1 (lines unique to FILE1)\n"
" -2 suppress column 2 (lines unique to FILE2)\n"
" -3 suppress column 3 (lines common to both)",
.extra = "",
};
} // namespace
auto comm_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'1', false},
cfbox::args::OptSpec{'2', false},
cfbox::args::OptSpec{'3', 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 suppress1 = parsed.has('1');
bool suppress2 = parsed.has('2');
bool suppress3 = parsed.has('3');
const auto& pos = parsed.positional();
if (pos.size() < 2) {
CFBOX_ERR("comm", "missing operand");
return 1;
}
auto lines1_result = cfbox::io::read_lines(std::string{pos[0]});
auto lines2_result = cfbox::io::read_lines(std::string{pos[1]});
if (!lines1_result) {
CFBOX_ERR("comm", "%s", lines1_result.error().msg.c_str());
return 1;
}
if (!lines2_result) {
CFBOX_ERR("comm", "%s", lines2_result.error().msg.c_str());
return 1;
}
const auto& lines1 = *lines1_result;
const auto& lines2 = *lines2_result;
std::size_t i = 0, j = 0;
while (i < lines1.size() && j < lines2.size()) {
if (lines1[i] < lines2[j]) {
if (!suppress1) std::printf("%s\n", lines1[i].c_str());
++i;
} else if (lines1[i] > lines2[j]) {
if (!suppress2) std::printf("\t%s\n", lines2[j].c_str());
++j;
} else {
if (!suppress3) std::printf("\t\t%s\n", lines1[i].c_str());
++i; ++j;
}
}
while (i < lines1.size()) {
if (!suppress1) std::printf("%s\n", lines1[i].c_str());
++i;
}
while (j < lines2.size()) {
if (!suppress2) std::printf("\t%s\n", lines2[j].c_str());
++j;
}
return 0;
}