I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:
1498493536984926976
I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:
time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date;
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);
However, this code SegFaults
on the strftime
line! I have no idea what is causing this. I have tried initializing buffer
as
char buffer[80];
and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string
; that hasn't worked either.
Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.
Any help would be appreciated!
These lines are your problem:
char *buffer;
strftime (buffer,sizeof(buffer),"%j",&date);
You've allocated a char *
but it doesn't point to anything. It's just a random value, so you're passing a wild pointer into strftime()
. Also, sizeof(buffer)
will be the size of the pointer (4 or 8 bytes depending on your architecture), not the size of the array that buffer is supposed to point at.
Change char * buffer
to char buffer[32];
or something like that.
Based on the fact they're supposed to be epoch times, your timestamps are in nanoseconds.
1498493536984926976s = 4.749E10 years
.
1498493536984926976ns = 47.49 years
.
Unless your time stamps really are 34 billion years into the future, you should convert them to seconds before sending them to localtime
to get a struct tm
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With