tx-gxx-linux/device/gxx-linux/packages/common.pkg/include/filetools.h

59 lines
1.2 KiB
C++

#pragma once
#include <vector>
#include <iostream>
#include <fstream>
#include <time.h>
#include <sstream>
#include <chrono>
class FileTools
{
private:
std::string mPath;
public:
FileTools(std::string path)
{
mPath = path;
}
void createLog(std::string log)
{
time_t now = time(0);
tm *ltm = localtime(&now);
char loc_date[30];
sprintf(loc_date, "%d%02d%02d %d:%d:%d", 1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
std::ofstream ofs(mPath);
ofs << loc_date << ": " << log << std::endl;
ofs.close();
}
void append_log(std::string log, bool printTime = true)
{
std::ofstream ofs(mPath, std::ios::app);
if (printTime)
{
time_t now = time(0);
tm *ltm = localtime(&now);
char loc_date[30];
sprintf(loc_date, "%d%02d%02d %d:%d:%d", 1900 + ltm->tm_year, 1 + ltm->tm_mon, ltm->tm_mday, ltm->tm_hour, ltm->tm_min, ltm->tm_sec);
ofs << loc_date << ": " << log << std::endl;
}
else
{
ofs << " " << log << std::endl;
}
ofs.close();
}
void clear()
{
try
{
std::fstream fout(mPath, std::ios::out | std::ios::trunc);
fout.close();
}
catch (std::exception &e)
{
//LOG("error happened: %s \n", e.what());
}
}
};