Write .log file

No. T01

写在前面:
放下LabVIEW选择C++半年有余,从零开始到能够参与项目模块开发,走不少弯路费不少精力,然在工作中发现基础不扎实导致效率低下也是时常发生。新的一年开始了,就想着夯实基础,整理头脑。
新开通博客也不知从何写起,就整理下工具吧,往后再使用时也就信手拈来了。

T01) 写日志文件:要求保留一个月数据。代码片段如下

#include <direct.h>
#include <time.h> 
#include <sys/stat.h>

//————————————————————————————————————————
void WriteToFile(char* path,char* Msg)
{
    struct stat temp;
    char su1[MAX_PATH];
    char su2[MAX_PATH];
    memcpy(su1,path,MAX_PATH);
    memcpy(su2,path,MAX_PATH);
    strcat(su1,".1");
    strcat(su2,".2");
    stat(path,&temp);
    int ss=temp.st_size;
    if (ss/1024/1024/1024>=1)
    {   
        DeleteFileA(su2);
        rename(su1,su2);
        rename(path,su1);               
    }   
    FILE *file=fopen(path,"a+");  
    fwrite(Msg,strlen(Msg),1,file);
    fclose(file);
    return;
}

void LogInfo()
{
    HINSTANCE dllModule = GetModuleHandleA("BH_PIN.dll"); 
    //日志路径.
    memset(mPath, 0, MAX_PATH);
    GetModuleFileNameA(dllModule, mPath, sizeof(mPath));
    *(strrchr(mPath, '\\') + 1) = 0;

    memset(mdllItem, 0, 1024);
    memcpy(mdllItem, mPath, strlen(mPath));
    strcat_s(mdllItem, "\\KMY350X.dll");
    strcat_s(mPath, "LOG\\");
    _mkdir(mPath);

    //产生日志名.
    time_t t = time(0);
    char LogName[64];
    strftime(LogName, sizeof(LogName), "PIN%Y%m%d.log", localtime(&t));
    strcat_s(PINpath, LogName);
    //删除日志
    int year, month, day;
    tm* tt = localtime(&t);
    year = tt->tm_year+1900;
    month = tt->tm_mon;
    day = tt->tm_mday;

    memset(LogName, 0, 64);
    if ( 0 == month )   //1月时删除上一年12月的日志
    {
        sprintf_s(LogName, "PIN%d%02d%02d.log", year-1, 12, day);
        strcat_s(mPath, LogName);
        DeleteFileA(mPath);
        return;
    }

    for (int i = 1; i < 13; i++)
    {
        if (i == month+1)   continue;
        CStringA szstr;
        szstr.Empty();
        szstr = mPath;
        int k = szstr.ReverseFind('\\');
        szstr = szstr.Left(k+1);
        sprintf_s(LogName, "PIN%d%02d%02d.log", year, i, day);
        szstr += LogName;
        bool bb = DeleteFileA(szstr.GetBuffer());
        if (bb)
        {
            time_t t = time(0);
            char tmp[128];
            strftime(tmp, sizeof(tmp), "<<%H:%M:%S#信息>>删除日志成功!", localtime(&t));
            strcat(tmp, szstr.GetBuffer());
            strcat(tmp, "\n");
            WriteToFile(mPath, tmp);
        }
    }
    return;
}

PS: 第一篇技术博客,难免有漏洞或错误,请多多指正。
本工具也是比较粗糙的,比如2月份时因为最多29天,那么1月份最后两天的数据就没法被删除完,只有等到3月份时才会被删除。然也能够实现需求,就这样吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值