本篇介绍time.h头文件中安全函数学习之asctime_s,ctime_s,gmtime_s,localtime_s。
实验环境:window11 Qt 5.12.9
asctime / asctime_s example
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <errno.h>
int main(void)
{
struct tm tm = *localtime(&(time_t){time(NULL)});
printf("%s", asctime(&tm)); // 注意隐含的末尾 '\n'
char str[26];
//errno_t __cdecl asctime_s (char *_Buf,size_t _SizeInWords,const struct tm *_Tm);
int ret = asctime_s(str, sizeof str, &tm); //返回为0表示正常,非0表示错误
printf("ret = %d \t %s", ret, str);
char str1[20];
ret = asctime_s(str1, sizeof str1, &tm);
printf("ret = %d \t %s", ret, str1);
return 0;
}
运行结果:
参考:
https://zh.cppreference.com/w/c/chrono/asctime
ctime / ctime_s example
#include <stdio.h>
#include <time.h>
#include <stdlib.h> // 为 putenv
#include <stdint.h>
#include <math.h>
#include <errno.h>
int main(void)
{
time_t result = time(NULL);
printf("%s", ctime(&result));
char str[26];
//ctime_s(char *_Buf, size_t _SizeInBytes, const time_t *_Time) { return _ctime64_s(_Buf,_SizeInBytes,_Time); }
int ret = ctime_s(str, sizeof str, &result);
printf("ctime_s ret = %d\t%s", ret, str);
char str1[20];
ret = ctime_s(str1, sizeof str1, &result);
printf("ctime_s ret = %d\t%s", ret, str1);
return 0;
}
运行结果:
参考:
https://zh.cppreference.com/w/c/chrono/ctime
gmtime / gmtime_s example
#include <stdio.h>
#include <time.h>
#include <stdlib.h> // 为 putenv
#include <stdint.h>
#include <math.h>
#include <errno.h>
int main(void)
{
time_t t = time(NULL);
printf("UTC: %s", asctime(gmtime(&t)));
printf("local: %s", asctime(localtime(&t)));
// POSIX 专有
putenv("TZ=Asia/Singapore");
printf("Singapore: %s", asctime(localtime(&t)));
struct tm buf;
char str[26];
//errno_t __cdecl gmtime_s(struct tm *_Tm, const time_t *_Time) { return _gmtime64_s(_Tm, _Time); }
int ret = gmtime_s(&buf, &t);
if(ret == 0)
{
//errno_t __cdecl asctime_s (char *_Buf,size_t _SizeInWords,const struct tm *_Tm);
ret = asctime_s(str, sizeof str, &buf);
}
printf("asctime_s ret = %d \t %s", ret, str);
return 0;
}
运行结果:
参考:
https://zh.cppreference.com/w/c/chrono/gmtime
localtime / localtime_s example
#include <stdio.h>
#include <time.h>
#include <stdlib.h> // 为 putenv
#include <stdint.h>
#include <math.h>
#include <errno.h>
int main(void)
{
time_t t = time(NULL);
printf("UTC: %s", asctime(gmtime(&t)));
printf("local: %s", asctime(localtime(&t)));
// POSIX 专有
putenv("TZ=Asia/Singapore");
printf("Singapore: %s", asctime(localtime(&t)));
struct tm buf;
char str[26];
//errno_t __cdecl localtime_s(struct tm *_Tm,const time_t *_Time) { return _localtime64_s(_Tm,_Time); }
int ret = localtime_s(&buf, &t);
if(ret == 0)
{
//errno_t __cdecl asctime_s (char *_Buf,size_t _SizeInWords,const struct tm *_Tm);
ret = asctime_s(str, sizeof str, &buf);
}
printf("localtime_s local:ret=%d%s", ret, str);
return 0;
}
运行结果:
参考:
https://zh.cppreference.com/w/c/chrono/localtime