pseudonym_127
pseudonym_127

Reputation: 357

Write a time_t variable to file

I am writing a time_t variable in a file like this (and also reading it in a same way, however, instead of write, now I use read):

//Write time

         file fd;
         time_t currentTime;
         currentTime = time(0); // current time
         fd.create(filepath);  
         fd.open(filepath);  
         fd.seek(SEEK_SET,0);  
         fd.write(&currentTime,sizeof(time_t));  
         fd.close();

// Read time

     file fd;
     time_t timeFromFile;
     fd.open(filepath);  
     fd.seek(SEEK_SET,0);  
     fd.read(&timeFromFile,sizeof(time_t));  

Is there something wrong with above approach? (Besides that it is working as I checked).

ps. I am writing for an embedded device, so I don't think portability etc. should be an issue. I think this will run mostly on similar type of devices.

Upvotes: 0

Views: 2468

Answers (2)

Steve
Steve

Reputation: 7271

time_t is not guaranteed to be an integral type in C++.

Although not defined, this is almost always a integral value holding the number of seconds since 00:00, Jan 1 1970 UTC, corresponding to POSIX time.

However, if you are always reading and writing from the same platform and compiler, it should be fine. It's worth noting whilst most systems represent time as an integral, some may have different sizes. Originally, time_t was frequently represented by a 32-bit number. However, this creates the 2038 problem. These days, it is common to see time_t being represented with a 64-bit number.

The year 2038 problem may cause some computer software to fail at some point near the year 2038. The problem affects all software and systems that both store system time as a signed 32-bit integer, and interpret this number as the number of seconds since 00:00:00 UTC on Thursday, 1 January 1970.

If you're compiling for different devices which use different header files (particulary ctime), you should be aware that there may be different sizes of time_t. If you write a time_t to a file that can be read from another build of your program, it is possible the size of the number will be different between the devices.

The best way to prevent problems is at compile time. If you're able to use a C++11 compiler, you can use static_assert.

static_assert( sizeof(time_t) == 8, "Unexpected time_t size" );

If the target you're compiling against uses a different size your code won't compile and will prevent unexplained errors. If you think this is a likely issue then you should serialize time yourself in another way.

Upvotes: 2

Barmar
Barmar

Reputation: 780871

According to POSIX:

time_t and clock_t shall be integer or real-floating types.

So it's perfectly reasonable to write them to a file like that, as long as you don't need to read them on a different device.

Upvotes: 1

Related Questions