多数时候需要以日志形式记录程序运行状态,日志的名称用时间(精确到秒)来命名可以避免重复
实例:
int CreateErrorLog()
{
string path = "F:\logpath";
char buffer[256];
buffer = path.c_str();
len = path.length();
if (_access(buffer, 0) == -1) // 判断存放日志的路径logpath文件夹是否存在
{
buffer[len++] = '\\';
int mRet = _mkdir(buffer); // 新建logpath路径
if (mRet)
{
printf("[Error]Failed to create directory:%s, exit\n", buffer);
return -1;
}
time_t timeTick = time(NULL);
strftime(buffer + len, _countof(buffer) - len, "Errlog_%Y%m%d%H%M%S.log", localtime(&timeTick));
buffer[_countof(buffer) - 1] = 0;
gErrorFile = fopen(buffer, "a");
if (gErrorFile == NULL)
{
printf("[Error]Failed to open file:%s, exit\n", buffer);
return -1;
}
}
else
{
buffer[len+++] = '\\';
time_t timeTick = time(NULL);
strftime(buffer + len, _countof(buffer) - len, "Errlog_%Y%m%d%H%M%S.log", localtime(&timeTick));
buffer[_countof(buffer) - 1] = 0;
gErrorFile = fopen(buffer, "a");
if (gErrorFile == NULL)
{
printf("[Error]Failed to open file:%s, exit\n", buffer);
return -1;
}
}
return 0;
}
这样便可在目录F:\logpath下创建类似Errlog_20170613155203.log格式的日志文件