-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtruncate.cpp
More file actions
71 lines (62 loc) · 2.03 KB
/
truncate.cpp
File metadata and controls
71 lines (62 loc) · 2.03 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
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cfbox/args.hpp>
#include <cfbox/fs_util.hpp>
#include <cfbox/help.hpp>
#include <cfbox/error.hpp>
namespace {
constexpr cfbox::help::HelpEntry HELP = {
.name = "truncate",
.version = CFBOX_VERSION_STRING,
.one_line = "shrink or extend the size of a file to the specified size",
.usage = "truncate -s SIZE FILE...",
.options = " -s SIZE set file size (supports K, M, G suffixes)",
.extra = "",
};
auto parse_size(const std::string& s) -> long {
char* end = nullptr;
long val = std::strtol(s.c_str(), &end, 10);
if (end == s.c_str()) return -1;
if (*end != '\0') {
switch (*end) {
case 'K': case 'k': val *= 1024; break;
case 'M': case 'm': val *= 1024 * 1024; break;
case 'G': case 'g': val *= 1024L * 1024 * 1024; break;
default: return -1;
}
}
return val;
}
} // namespace
auto truncate_main(int argc, char* argv[]) -> int {
auto parsed = cfbox::args::parse(argc, argv, {
cfbox::args::OptSpec{'s', true, "size"},
});
if (parsed.has_long("help")) { cfbox::help::print_help(HELP); return 0; }
if (parsed.has_long("version")) { cfbox::help::print_version(HELP); return 0; }
auto size_str = parsed.get_any('s', "size");
if (!size_str) {
CFBOX_ERR("truncate", "missing operand: -s SIZE");
return 1;
}
long size = parse_size(std::string{*size_str});
if (size < 0) {
CFBOX_ERR("truncate", "invalid size: '%.*s'", static_cast<int>(size_str->size()), size_str->data());
return 1;
}
const auto& pos = parsed.positional();
if (pos.empty()) {
CFBOX_ERR("truncate", "missing operand");
return 1;
}
int rc = 0;
for (auto p : pos) {
auto result = cfbox::fs::resize_file(std::string{p}, static_cast<std::uintmax_t>(size));
if (!result) {
CFBOX_ERR("truncate", "%s", result.error().msg.c_str());
rc = 1;
}
}
return rc;
}