C++日志模块&文本文件输出模块

sdl检测关掉,不然springf会报错,说不安全。
项目-属性-C+±sdl检测设为“否”
在这里插入图片描述

#include<iostream>
#include<string>
#include<thread>
#include<Windows.h>
#include<fstream>
#include<cstdio>
using namespace std;
bool WriteText(string sText)
{
    SYSTEMTIME st;
    char* cDat = new char[1024];
    char* cTime = new char[1024];
    char* cValue = new char[1024];
    char* cText = new char[1024];

    ZeroMemory(cDat,1024);          //数组初始化,如果不初始化会乱码
    ZeroMemory(cTime, 1024);
    ZeroMemory(cValue, 1024);
    ZeroMemory(cText, 1024);

    int nYear, nMonth, nDay, nHour, nMin, nSecond;
    string sPathName;

    GetLocalTime(&st);//获取系统日期
    nYear = st.wYear;
    nMonth = st.wMonth;
    nDay = st.wDay;
    nHour = st.wMonth;
    nMin = st.wSecond;

    sprintf(cDat, "%.4d-%.2d-%.2d", st.wYear, st.wMonth, st.wDay);         //将整型变量转换成字符串
    sprintf(cTime, "%.2d:%.2d:%.2d  ", st.wHour, st.wMinute, st.wSecond);
    sprintf(cValue, "%s %s",cDat, cTime);                   //将字符串合并
    sText = cTime + sText;
    sprintf(cText,sText.c_str());                           //string赋值给char*

    sPathName = cDat;
    sPathName ="ThreadLog\\"+sPathName + ".txt";//最终的路径

    cout << "cDat: " << cDat << "cTime: " << cTime << endl;
    cout << "cValue: " << cValue << endl;
    cout << "sPathNmae: " << sPathName << endl;
    cout << "cText" << cText << endl;
    
    ofstream OutFile;
    OutFile.open(sPathName,fstream::out | fstream::app);//写入,创建,追加
    OutFile.write(cText,strlen(cText));
    OutFile.close();

    cDat = NULL;//因为要经常调用,记得释放资源
    cTime = NULL;
    cValue = NULL;
    cText = NULL;
    delete[] cDat;
    delete[] cTime;
    delete[] cValue;
    delete[] cText;

    return true;
}

void main()
{
    string s;
    while (true)
    {
        cin >> s;
        s += "\r";
        if (WriteText(s))
            cout << "写入成功" << endl;
        else
        {
            cout << "写入失败" << endl;
        }
    }
	system("pause");
	return;
}


保存的文件在放cpp文件的地方,只要鼠标右键,打开文件所在地就能找到文件夹了(ThreadLog)在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值