How to store time_t timestamp in a file using C?

For the small todo program that I am writing, I have timestamps that have this form

time_t t = time(NULL); 

and saved each time a task is specified to indicate the time it was entered.

I want to save tasks in a text file so that the state can be saved and restored. How to store timestamps in a text file and how can I return them to my program after reading a text file?

+6
c file datetime time file-io
source share
3 answers

Convert time_t to struct tm with gmtime() , then convert struct tm to plain text (preferably in ISO 8601 format) using strftime() . The result will be portable, readable and machine readable.

To return to time_t , you simply parse the string back into struct tm and use mktime() .

For reference:

Code example:

 // Converting from time_t to string time_t t = time(NULL); struct tm *ptm = gmtime(&t); char buf[256]; strftime(buf, sizeof buf, "%F %T", ptm); // buf is now "2015-05-15 22:55:13" // Converting from string to time_t char *buf = "2015-05-15 22:55:13"; struct tm tm; strptime(buf, "%F %T", &tm); time_t t = mktime(&tm); 
+12
source share

the portable method uses the difftime function. Calculate time_t for the selected era using mktime , then use difftime to calculate the difference in seconds. To convert back, you can start with an era like struct tm and add the number of seconds to tm_sec , then call mktime to get time_t .

A reasonable way is to assume that time_t is represented as the second since Unix (1970-01-01 00:00 GMT) and is converted to a large integer type ( long long is best) for printing. POSIX requires a time_t second from the era, and on any reasonable system it will.

+3
source share

If you don't mind a few unmanaged assumptions, just drop time_t to long ( long long if you have a C99 compiler), write a long value, read the value, and return time_t .

The standard does not guarantee that time_t seems even long: it only says that time_t is an arithmetic type, but the trick above should work for all reasonable systems :-)

+1
source share

All Articles