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
|
#include "logit.h"
#include <limits.h>
Logit::Logit(const char *filename, bool is_verbose, bool numbered_files, int pid)
: m_verbose(is_verbose)
, m_fp(NULL)
, m_count(0)
, m_numbered_files(numbered_files)
, m_filename(filename)
, m_pid(pid)
{
}
Logit::Logit(const Logit &l, int pid)
: m_verbose(l.m_verbose)
, m_fp(NULL)
, m_count(0)
, m_numbered_files(l.m_numbered_files)
, m_filename(l.m_filename)
, m_pid(pid)
{
}
bool Logit::reopen()
{
if(!m_numbered_files && m_fp)
return false;
char buf[PATH_MAX];
if(m_fp)
{
fflush(m_fp);
fclose(m_fp);
}
char pid[12], count[12];
sprintf(pid, "%d", m_pid);
sprintf(count, "%d", m_count);
strncpy(buf, m_filename.c_str(), PATH_MAX - 25);
buf[PATH_MAX - 25] = '\0';
if(m_pid)
{
strcat(buf, ":");
strcat(buf, pid);
}
if(m_numbered_files)
{
strcat(buf, ":");
strcat(buf, count);
}
m_count++;
m_fp = fopen(buf, "w");
if(!m_fp)
{
fprintf(stderr, "Can't open file %s\n", buf);
m_fp = fdopen(2, "w");
}
return false;
}
Logit::~Logit()
{
fflush(m_fp);
fclose(m_fp);
}
int Logit::Write(const char *data, size_t len)
{
if(!m_fp)
reopen();
if(fwrite(data, 1, len, m_fp) != len)
return -1;
fflush(m_fp);
return 0;
}
|