-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpiperoller.cpp
More file actions
114 lines (104 loc) · 2.65 KB
/
piperoller.cpp
File metadata and controls
114 lines (104 loc) · 2.65 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
#include <csignal>
#include <fstream>
#include <iostream>
#include <stdio.h>
using namespace std;
namespace // anonymous
{
volatile sig_atomic_t gSignalStatus;
void usage()
{
cerr << "Usage: piperoller basename [starting_number]" << endl;
}
int init(const string& basename, int seq, ofstream& strm)
{
string filename(basename + "." + to_string(seq));
strm.open(filename);
if (!strm)
{
cerr << "Failed to open file \"" << filename << "\" for writing"
<< endl;
return 1;
}
return 0;
}
std::string my_time(void)
{
time_t tt;
struct tm tm;
char buf[128];
if ((tt = time (NULL)) == -1)
{
perror ("time failed");
pthread_exit (NULL);
}
tm = *localtime (&tt);
snprintf (buf, sizeof(buf), "%04d/%02d/%02d %02d:%02d:%02d",
tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
return std::string(buf);
}
int roll(const string& basename, int& seq, ofstream& strm)
{
strm << my_time() << " *** piperoller ***" << std::endl;
strm.close();
int retval = init (basename, ++seq, strm);
if (retval == 0)
{
strm << my_time() << " *** piperoller ***" << std::endl;
}
return retval;
}
} // namespace (anonymous)
extern "C" void signal_handler (int signal)
{
gSignalStatus = signal;
}
int main (int argc, char* argv[])
{
// Process inputs
if ((argc != 2) && (argc != 3))
{
usage();
return 1;
}
// Open first output file
int sequence = 0;
if (argc == 3)
{
if (sscanf (argv[2], "%d", &sequence) != 1)
{
cerr << "Error: illegal numeric expression \"" << argv[2] <<
"\"" << endl;
exit (1);
}
if (sequence < 0)
{
cerr << "Warning: sequence start will be negative" << endl;
}
}
ofstream outp;
if (init (argv[1], sequence, outp) != 0) return 1;
// Start handling the hang-up signal
signal (SIGHUP, signal_handler);
// Loop over input characters
int chr;
while ((chr = getchar()) != EOF)
{
if (chr == '\n')
{
outp << endl;
// Handle any signals that have come in since last line feed
if (gSignalStatus)
{
if (roll(argv[1], sequence, outp) != 0) return 1;
gSignalStatus = 0;
}
}
else
{
outp << static_cast<char>(chr);
}
}
return 0;
}