The C++ program records the log with the system time as the file name

Recently, when adding a piece of code to an existing MFCprogram, I found that Release x64the code cannot print variable information on the console in the environment, so I used the method of writing a file to observe the variable information output when debugging the program.

C++Writing content to a text file is to use ofstreamclasses, but I want to use the system time as the text file name to record each debug information, for example:2022-08-26 14-45-25.txt

The sample code is as follows

#include <iostream>
#include <fstream>
#include "windows.h"

using namespace std;
SYSTEMTIME sys;

int main()
{
    
    
	ofstream ofs;

	string s = "day day up";
	char fileName[256];
	GetLocalTime(&sys);
	sprintf_s(fileName, "./log/%02d-%02d-%02d %02d-%02d-%02d.txt", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond);

	ofs.open(fileName, ios::out);

	ofs << "today's log : " << endl;
	ofs << s << endl;

	ofs.close();

	return 0;
}

output result

insert image description here

insert image description here

Guess you like

Origin blog.csdn.net/Star_ID/article/details/126543277