Joseph
Joseph

Reputation: 1

How to save the log messages into the text file

I am currently doing on the timestamp on the robot and I have managed to display the results on it. However, I would like to know on how to save the information to the text file. I am currently using C++ compiler

const std::string currentDateTime() {
    time_t now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);

    strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);

    return buf;
   
    std::cout << currentDateTime() << " Robot 1" << std::endl;
}

Upvotes: 0

Views: 452

Answers (1)

Daniel Junglas
Daniel Junglas

Reputation: 5930

Instead of printing to std::cout you can print to a std::ofstream:

#include <fstream>

std::ofstream logfile("logfile", std::ofstream::out); // or std::ofstream::app to append
logfile << currentDateTime() << " Robot 1" << std::endl

Maybe you want to add error checking in case the logfile cannot be openend/created.

Upvotes: 1

Related Questions