使用C ++中的日期和时间命名日志文件

时间:2014-11-20 15:26:26

标签: c++

所以,我想为我想要创建的应用创建一个日志文件,而且我不知道如何将日志命名为" 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;
}

3 个答案:

答案 0 :(得分:1)

您应该使用支持通过重载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

答案 1 :(得分:0)

你实际的问题是“为什么这不起作用”

 myfile.open ("log/" + buffer);

回答 - 因为c ++不支持你想要的东西 - 将字符串文字与char *连接起来并返回另一个char *。

DO

std::string filetime(buffer);

std::string filename = "log/" + filetime;

open(filename.c_str());

答案 2 :(得分:0)

考虑使用std :: facilities(std :: string和std :: ostringstream):

std::ostream& time_digits(std::ostream& out, unsigned int digits)
{ // convenience function: apply width and fill for the next input
    return out << std::setw(digits) << std::setfill('0');
}

std::string unique_log_name()
{ // generate unique log name, depending on local time
  // example output: "log/2014-04-19.log"

    auto now = time(0);
    tm *ltm = localtime(&now);

    std::ostringstream buffer;
    buffer
        << "log/" << time_digits(4) << ltm.tm_year
        << "-" << time_digits(2) << ltm.tm_mon
        << "-" << time_digits(2) << ltm.tm_day;

    // could also add these to the name format:
    // buffer
    //     << "-" << time_digits(2) << ltm.dm_hour
    //     << "-" << time_digits(2) << ltm.tm_min
    //     << "-" << time_digits(2) << ltm.tm_sec;

    buffer << ".log"; // add extension

    return buffer.str();
}

void client_code()
{ // construct log stream on unique file name
    ofstream myfile{ unique_log_name() };
    if(myfile)
    {
        cout << "Success" << std::endl;
    }
}