Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I store a time_t timestamp to a file using C?

For a small todo program that I am writing, I have timestamps that are of this form

time_t t = time(NULL);

and are saved every time a task is entered to denote the time that it was entered.

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

like image 897
Lazer Avatar asked Nov 06 '10 16:11

Lazer


People also ask

How to store time in C?

The time() function is defined in time. h (ctime in C++) header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.

What is a timestamp in C?

timestamp, a C code which prints the YMDHMS date as a timestamp. This is useful when documenting the run of a program. By including a timestamp, the output of the program will always contain a clear indication of when it was created.

How to check system time in C?

C Program to Display the current Date and Time The C library function char *ctime(const time_t *timer) returns a string representing the localtime based on the argument timer. The returned string has the following format: Www Mmm dd hh:mm:ss yyyy.


1 Answers

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

To get back to the time_t, you just parse the string back into a struct tm and use mktime().

For reference:

  • gmtime
  • strftime
  • strptime
  • mktime

Code sample:

// 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);
like image 69
mu is too short Avatar answered Sep 20 '22 13:09

mu is too short