tags:

views:

123

answers:

3

hi, 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?

A: 

Hi blood,

Maybe this would work?:

time_t rawtime;

time ( &rawtime ); header << "The time is: %s" + ctime (&rawtime);

Hope this works

lucifer
sorry no "error C2110: '+' : cannot add two pointers":( o well thank you anyway
blood
+1  A: 

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
paxdiablo
Hmm this works xD tyvm (but btw you forgot to #include <time.h>)
blood
Good point, blame it on gcc for being so forgiving :-) Fixed it up for future generations.
paxdiablo
A: 

A really good tip is to check out the boost\date_time library. It is great, it got everything you need supports simple output and formatting and is portable.

Worth checking out.

daramarak