(C++) Aktuelle Zeit und Datum in Datei schreiben

Mit der timelib.

Beispiel:
Code:
#include <fstream>
#include <sstream>

#include <time.h>

using namespace std;

int main()
{
    time_t Zeitstempel;
    tm *nun;
    Zeitstempel = time(0);
    nun = localtime(&Zeitstempel);

    stringstream zeit_buendel;
    zeit_buendel << nun->tm_mday << '.' << nun->tm_mon+1 << '.'
                 << nun->tm_year+1900 << " - " << nun->tm_hour
                 << ':' << nun->tm_min << endl;

    ofstream timewrite("zeit.txt");
    timewrite << zeit_buendel.str().c_str();

    return 0;
}

Gruß Hallasas

EDIT:
Hier aus der time.h:
Code:
struct tm {
   int tm_sec;      /* Sekunden - [0,61] */
   int tm_min;      /* Minuten - [0,59] */
   int tm_hour;     /* Stunden - [0,23] */
   int tm_mday;     /* Tag des Monats - [1,31] */
   int tm_mon;      /* Monat im Jahr - [0,11] */
   int tm_year;     /* Jahr seit 1900 */
   int tm_wday;     /* Tage seit Sonntag (Wochentag) - [0,6] */
   int tm_yday;     /* Tage seit Neujahr (1.1.) - [0,365] */
   int tm_isdst;    /* Sommerzeit-Flag */
}
 
Zuletzt bearbeitet:
Ach ja, wenns 17:01 Uhr (z.B.) ist, wird 17:1 ausgegeben. Das habe ich so gelöst:
C++:
if(nun->tm_min>9)
    outfile<<nun->tm_min;
else
    outfile<<'0'<<nun->tm_min;
(Ich habe jetzt kein "Zeitbündel" genommen, sondern alles einzeln per outfile ausgegeben)
Gibt es da noch eine andere Möglichkeit?
 
Hallo,

zwei Alternativen:
1. strftime
C++:
#include <ctime>
#include <fstream>

using namespace std;

int main() {
    time_t now = time(0);
    char timestamp[22];
    strftime(timestamp, 22, "%d.%m.%Y - %H:%M:%S", localtime(&now));

    ofstream logfile("test.log", ios::out | ios::app);
    logfile << timestamp << endl;
    logfile.close();

    return 0;
}

2. Boost.Date_Time, wobei ich mich damit selber noch nicht näher beschäftigt habe.

Grüße,
Matthias
 
Zurück