-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrev.cpp
More file actions
64 lines (56 loc) · 1.61 KB
/
rev.cpp
File metadata and controls
64 lines (56 loc) · 1.61 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
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <cfbox/applet.hpp>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "rev",
.version = CFBOX_VERSION_STRING,
.one_line = "reverse lines characterwise",
.usage = "rev [FILE...]",
.options = "",
.extra = "",
};
auto process_stream(std::FILE* f) -> void {
char buf[4096];
while (std::fgets(buf, sizeof(buf), f)) {
auto len = std::strlen(buf);
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) {
buf[--len] = '\0';
}
std::reverse(buf, buf + len);
std::printf("%s\n", buf);
}
}
} // anonymous namespace
auto rev_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
const auto& pos = parsed.positional();
if (pos.empty()) {
process_stream(stdin);
return 0;
}
int rc = 0;
for (const auto& filename : pos) {
auto fn = std::string(filename);
if (fn == "-") {
process_stream(stdin);
} else {
auto* f = std::fopen(fn.c_str(), "r");
if (!f) {
CFBOX_ERR("rev", "cannot open %s", fn.c_str());
rc = 1;
continue;
}
process_stream(f);
std::fclose(f);
}
}
return rc;
}