-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
121 lines (113 loc) · 3.02 KB
/
main.cpp
File metadata and controls
121 lines (113 loc) · 3.02 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <fstream>
#include <iostream>
#include <cstring>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
/**
* stomp - Simple utility to truncate file(s)
*
* A useful utility for files such as logs that need to exist but be made empty.
*
* Generally ignores exceptions.
*
* 1.0 Initial implementation, 14 Feb 2019
* 1.1.0 Added -d delete option, 9 Mar 2019
*/
char *arg;
bool isDelete = false;
bool quiet = false;
bool argIs(const char *cmp);
void parseOptions(int argc, char **argv);
void stompArguments(int argc, char **argv);
void usage();
int main(int argc, char* argv[])
{
parseOptions(argc, argv);
stompArguments(argc, argv);
return 0;
}
bool argIs(const char *cmp)
{
return strcmp(arg, cmp) == 0;
}
void parseOptions(int argc, char **argv)
{
// if there are no arguments show usage
if (argc < 2) // program path is argv[0]
{
usage();
exit(0);
}
for (int i = 1; i < argc; ++i) // skip program path argv[0]
{
arg = argv[i];
if (arg[0] == '-') // skip non-options
{
if (argIs("-d"))
{
isDelete = true;
}
else if (argIs("-q"))
{
quiet = true;
}
else if (argIs("-?") || argIs("-h") || argIs("--help"))
{
usage();
exit(0);
}
}
}
}
void stompArguments(int argc, char **argv)
{
int count = 0;
for (int i = 1; i < argc; ++i)
{
char *arg = argv[i];
if (arg[0] != '-') // skip options
{
try
{
if (isDelete) {
remove(arg);
}
else {
std::fstream fs(arg, std::fstream::out | std::fstream::trunc);
}
++count;
}
catch(const std::runtime_error& re)
{
//std::cerr << "Runtime error: " << re.what() << std::endl;
}
catch(const std::exception& ex)
{
//std::cerr << "Error occurred: " << ex.what() << std::endl;
}
if ( ! quiet)
{
std::cout << (isDelete ? "deleted " : "stomped ") << argv[i] << std::endl;
}
}
}
if ( ! quiet)
{
std::cout << (isDelete ? "deleted " : "stomped ") << count << " files" << std::endl;
}
}
void usage()
{
std::cout << "" << std::endl;
std::cout << "stomp v1.1.0 - Truncate one or more files" << std::endl;
std::cout << "" << std::endl;
std::cout << "Usage: stomp [-q] file1 file2 ..." << std::endl;
std::cout << "" << std::endl;
std::cout << "Options:" << std::endl;
std::cout << " -d Delete the file instead of truncating" << std::endl;
std::cout << " -q Quiet, do not output anything" << std::endl;
std::cout << "" << std::endl;
std::cout << "If a path or filename contains spaces enclose it in double-quotes." << std::endl;
std::cout << "" << std::endl;
}