Monday, December 4, 2017

C++17(C11): Bounds-checking asctime_s(), ctime_s(), gmtime_s(), and localtime_s()

C++17 added the bounds-checking functions asctime_s(), ctime_s(), gmtime_s(), and localtime_s().

#include <ctime>
#include <iostream>
using namespace std;

int main()
{
  time_t    currentTime = 0;
  struct tm currentTm;
  char      buffer[32];

  localtime_s(&currentTm, &currentTime);
  asctime_s(buffer, sizeof(buffer), &currentTm);
  cout << buffer; // Wed Dec 31 19:00:00 1969

  ctime_s(buffer, sizeof(buffer), &currentTime);
  cout << buffer; // Wed Dec 31 19:00:00 1969

  gmtime_s(&currentTm, &currentTime);
  asctime_s(buffer, sizeof(buffer), &currentTm);
  cout << buffer; // Thu Jan  1 00:00:00 1970

  cout << endl;  
  return 0;
}
// Output: Wed Dec 31 19:00:00 1969
//         Wed Dec 31 19:00:00 1969
//         Thu Jan  1 00:00:00 1970
References:
http://en.cppreference.com/w/c/chrono/asctime
http://en.cppreference.com/w/c/chrono/ctime
http://en.cppreference.com/w/c/chrono/gmtime
http://en.cppreference.com/w/c/chrono/localtime

No comments:

Post a Comment