how do i save time to a file?

10,661

This is how I'd do it, with a helper function that just gave you the date and time in your desired format for inclusion into any output stream:

#include <time.h>
#include <iostream>
#include <fstream>
using namespace std;

// Helper function for textual date and time.
// DTTMSZ must allow extra character for the null terminator.

#define DTTMFMT "%Y-%m-%d %H:%M:%S "
#define DTTMSZ 21
static char *getDtTm (char *buff) {
    time_t t = time (0);
    strftime (buff, DTTMSZ, DTTMFMT, localtime (&t));
    return buff;
}

int main(void) {
    char buff[DTTMSZ];
    fstream filestr;
    filestr.open ("test.txt", fstream::out|fstream::app);

    // And this is how you call it:
    filestr << getDtTm (buff) << "Your message goes here" << std::endl;

    filestr.close();

    return 0;
}

This creates the file test.txt with the contents:

2010-05-05 13:09:13 Your message goes here
Share:
10,661
blood
Author by

blood

Updated on June 25, 2022

Comments

  • blood
    blood almost 2 years

    i have a program that saves data to file and i want to put a time stamp of the current date/time on that log but when i try to write the time to the file it will not show up but the other data i write will.

    #include <iostream>
    #include <windows.h>
    #include <fstream>
    #include <string>
    #include <sstream>
    #include <direct.h>
    #include <stdio.h>
    #include <time.h>
    
    using namespace std;
    
    string header_str = ("NULL");
    
    
    int main()
    {
    
    for(;;)
    {
    
    
            stringstream header(stringstream::in | stringstream::out);   
    
            header << "datasdasdasd_";
    
             time_t rawtime;
    
             time ( &rawtime );
    
            header << ctime (&rawtime);
            header_str = header.str();
    
            fstream filestr;
    
            filestr.open ("C:\\test.txt", fstream::in | fstream::out |   fstream::app | ios_base::binary | ios_base::out);
    
            for(;;)
            {
                filestr << (header_str);
    
            }
    
            filestr.close();
    
    
    }
    
    return 0;
    }
    

    anyone know how to fix this?