-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcat.cpp
More file actions
106 lines (90 loc) · 2.83 KB
/
cat.cpp
File metadata and controls
106 lines (90 loc) · 2.83 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <cstdio>
#include <string_view>
#include <cfbox/args.hpp>
#include <cfbox/help.hpp>
#include <cfbox/io.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "cat",
.version = CFBOX_VERSION_STRING,
.one_line = "concatenate files and print on the standard output",
.usage = "cat [OPTIONS] [FILE]...",
.options = " -n number all output lines\n"
" -b number nonempty output lines\n"
" -A show all nonprinting chars, display $ at end of line",
.extra = "",
};
auto print_visible_char(unsigned char c) -> void {
if (c >= 128) {
std::fputs("M-", stdout);
c -= 128;
}
if (c < 32 && c != '\t') {
std::fputc('^', stdout);
std::fputc(c + 64, stdout);
} else if (c == 127) {
std::fputs("^?", stdout);
} else {
std::fputc(c, stdout);
}
}
auto cat_stream(std::FILE* f, bool n_flag, bool b_flag, bool A_flag) -> void {
int line_num = 1;
bool at_line_start = true;
int ch;
while ((ch = std::fgetc(f)) != EOF) {
if (at_line_start && (n_flag || b_flag)) {
bool non_empty = (ch != '\n');
if (!b_flag || non_empty) {
std::printf("%6d\t", line_num++);
}
}
if (ch == '\n') {
if (A_flag) std::fputc('$', stdout);
std::fputc('\n', stdout);
at_line_start = true;
} else if (A_flag) {
print_visible_char(static_cast<unsigned char>(ch));
at_line_start = false;
} else {
std::fputc(ch, stdout);
at_line_start = false;
}
}
}
auto cat_file(std::string_view path, bool n_flag, bool b_flag, bool A_flag) -> int {
if (path == "-") {
cat_stream(stdin, n_flag, b_flag, A_flag);
return 0;
}
auto result = cfbox::io::open_file(path, "rb");
if (!result) {
CFBOX_ERR("cat", "%s", result.error().msg.c_str());
return 1;
}
cat_stream(result->get(), n_flag, b_flag, A_flag);
return 0;
}
} // namespace
auto cat_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'n', false},
cfbox::args::OptSpec{'b', false},
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 n_flag = parsed.has('n');
bool b_flag = parsed.has('b');
bool A_flag = parsed.has('A');
const auto& pos = parsed.positional();
if (pos.empty()) {
return cat_file("-", n_flag, b_flag, A_flag);
}
int rc = 0;
for (const auto& p : pos) {
if (cat_file(p, n_flag, b_flag, A_flag) != 0) rc = 1;
}
return rc;
}