I managed to convert a time point into an integer and write it into a file using code that looks like the following code:
std::ofstream outputf("data");
std::chrono::time_point<std::chrono::system_clock> dateTime;
dateTime = std::chrono::system_clock::now();
auto dateTimeSeconds = std::chrono::time_point_cast<std::chrono::seconds>(toSerialize->dateTime);
unsigned long long int serializeDateTime = toSerialize->dateTime.time_since_epoch().count();
outputf << serializeDateTime << "\n";
Now I'm trying to read that integer from the file, convert it into a time_point, and print it. Right now, my code looks something like this:
std::ifstream inputf("data");
unsigned long long int epochDateTime;
inputf >> epochDateTime;
std::chrono::seconds durationDateTime(epochDateTime);
std::chrono::time_point<std::chrono::system_clock> dateTime2(durationDateTime);
std::time_t tt = std::chrono::system_clock::to_time_t(dateTime2);
char timeString[30];
ctime_s(timeString, sizeof(timeString), &tt);
std::cout << timeString;
However, it doesn't print anything. Does anyone know where I went wrong?
CodePudding user response:
Putting aside the possibility of the wrong date value, the problem here is with sizeof(timeString)
. It appears that you think it is 30
, but it in fact is the size of the char*
, likely 8 (or maybe 4).
According to ctime_s:
the following errors are detected at runtime and call the currently installed constraint handler function:
buf or timer is a null pointer bufsz is less than 26 or greater than RSIZE_MAX
CodePudding user response:
You have some strange conversions and assign to a variable that you don't use. If you want to store system_clock::time_point
s as std::time_t
s and restore the time_point
s from those, don't involve other types and use the functions made for this: to_time_t
and from_time_t
. Also, check that opening the file and that extraction from the file works.
Example:
#include <chrono>
#include <fstream>
#include <iostream>
int main() {
{ // save a time_point as a time_t
std::ofstream outputf("data");
if(outputf) {
std::chrono::time_point<std::chrono::system_clock> dateTime;
dateTime = std::chrono::system_clock::now();
outputf << std::chrono::system_clock::to_time_t(dateTime) << '\n';
}
}
{ // restore the time_point from a time_t
std::ifstream inputf("data");
if(inputf) {
std::time_t epochDateTime;
if(inputf >> epochDateTime) {
// use epochDateTime with ctime-like functions if you want:
std::cout << ctime(&epochDateTime) << '\n';
// get the time_point back (usually rounded to whole seconds):
auto dateTime = std::chrono::system_clock::from_time_t(epochDateTime);
// ...
}
}
}
}