roboticonx8
roboticonx8

Reputation: 39

Naming a log file using date and time in C++

So, I want to create a log file for an app I am trying to create and I don't know how to name the log to something like "log/date&time"

Anyway, here is my code:

#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;
}

Upvotes: 0

Views: 1937

Answers (3)

utnapistim
utnapistim

Reputation: 27365

Consider using std:: facilities instead (std::string and std::ostringstream come to mind):

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;
    }
}

Upvotes: 0

Columbo
Columbo

Reputation: 60979

You should use std::string which supports concatenation via the overloaded 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

Upvotes: 1

pm100
pm100

Reputation: 50120

you actual question is "why doesnt this work"

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

answer - because c++ doesnt support what you want - concatenate a string literal with a char * and return another char *.

do

std::string filetime(buffer);

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

open(filename.c_str());

Upvotes: 0

Related Questions