gpt4 book ai didi

c++ - 在 C++ 中使用日期和时间命名日志文件

转载 作者:行者123 更新时间:2023-11-28 06:34:05 25 4
gpt4 key购买 nike

所以,我想为我正在尝试创建的应用程序创建一个日志文件,但我不知道如何将日志命名为“log/date&time”之类的名称

无论如何,这是我的代码:

#include <iostream>
#include <fstream>
#include <time.h>
#include <stdio.h>
#include <sstream>


using namespace std;


int main (int argc, char *argv[])
{

time_t t = time(0);
struct tm * now = localtime( & t );

char buffer [80];
strftime (buffer,80,"%Y-%m-%d.",now); //i think i can't just put "log/%Y-%m-%d." there.

ofstream myfile;
myfile.open ("log/" + buffer); // this is my problem, i can't put the ' "log/" + ' part there
if(myfile.is_open())
{
cout<<"Success"<<std::endl;
}

return 0;
}

最佳答案

您应该使用 std::string,它支持通过重载的 operator+ 进行连接。

std::string buffer(80, '\0');
strftime( &buffer[0], buffer.size(), "some format string", now);

/* ... */
std::ofstream myfile( ("log/" + buffer).c_str() );
// Remove the (..).c_str() part when working with a C++11 conforming
// standard library implementation

关于c++ - 在 C++ 中使用日期和时间命名日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27043252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com