Zeit schreiben und wieder auslesen



  • Ich habe ein Programm, das die momentane Systemzeit in ein Textdokument "data.txt" schreibt.

    #include <fstream>
    #include <chrono>
    #include <ctime>
    #include <string>
    
    using namespace std;
    typedef chrono::system_clock Clock;
    
    int main() {
    
    Clock::time_point now = Clock::now();
    time_t tOutput = Clock::to_time_t(now);
    fstream file("data.txt", ios::out);
    char* output = ctime(&tOutput);
    file << endl << output;
    flush(file);
    file.close();
    }
    

    data.txt.
    Wed Jul 06 14:46:43 2016

    Nun möchte ich diese Zeit wieder in time_t konvertieren. Eingelesen habe ich die Zeit schon als

    char* time
    

    . Gibt es da irgendeine einfache Möglichkeit?



  • Hallo Shedex,

    Willkomme im C++-Forum.

    Für das Schreiben und Lesen von Datum und Uhrzeit gibt es die Manipulatoren put_- und get_time.
    Anbei ein Beispiel:

    #include <fstream>
    #include <chrono>
    #include <ctime>    // std::tm, localtime
    #include <iomanip>  // std::put_time, get_time
    #include <iostream> // cerr, cout, etc.
    
    typedef std::chrono::system_clock Clock;
    
    int main() {
        using namespace std;
        //                  Wed Jul 06 16:42:10 2016
        const char* format = "%a %b %d %H:%M:%S %Y";
        Clock::time_point now = Clock::now();
        time_t now_time_t = Clock::to_time_t(now);
        {
            ofstream file("data.txt");
            file << put_time( localtime( &now_time_t ), format ) << endl;
        }   // } -> file -> flush&close
    
        cout << "Bitte einen Moment warten und dann 'return' druecken >";
        cin.get();
    
        {
            ifstream file_in("data.txt");
            if( !file_in.is_open() )
            {
                cerr << "Fehler beim Oeffnen der Datei" << endl;
                return 0;
            }
            tm aTime;
            if( file_in >> get_time( &aTime, format ) )
            {
                auto vorher = Clock::from_time_t( mktime( &aTime ) );
                cout << "Seit dem Schreiben sind " << chrono::duration_cast< chrono::seconds >(Clock::now() - vorher).count() << "s vergangen" << endl;
            }
        }
        return 0;
    }
    

    Gruß
    Werner


Anmelden zum Antworten