_strtime_s_wstrtime_s

将当前时间复制到缓冲区。 这些函数的版本是 _strtime_wstrtime,具有安全性增强功能,如 CRT 中的安全功能中所述。

语法

errno_t _strtime_s(
   char *buffer,
   size_t numberOfElements
);
errno_t _wstrtime_s(
   wchar_t *buffer,
   size_t numberOfElements
);
template <size_t size>
errno_t _strtime_s(
   char (&buffer)[size]
); // C++ only
template <size_t size>
errno_t _wstrtime_s(
   wchar_t (&buffer)[size]
); // C++ only

参数

buffer
至少为 10 个字节长的缓冲区,将在其中写入时间。

numberOfElements
缓冲区的大小。

返回值

如果成功,则返回 0。

如果出现错误条件,则将调用无效的参数处理程序,如参数验证中所述。 如果失败,则返回值为错误代码。 错误代码在 ERRNO.H 中定义;有关此函数生成的确切错误,请参阅下表。 有关错误代码的详细信息,请参阅 errno 常数

错误条件

buffer numberOfElements 返回值 buffer 的内容
NULL (任意数值) EINVAL 未修改
NULL(指向有效的缓冲区) 0 EINVAL 未修改
NULL(指向有效的缓冲区) 0 < size < 9 EINVAL 空字符串
NULL(指向有效的缓冲区) Size > 9 0 注解中指定的当前时间格式

安全问题

如果 numberOfElements 参数大于 9,则为缓冲区传入无效非 NULL 值将导致访问冲突。

numberOfElements 传递的值大于缓冲区的实际大小将导致缓冲区溢出。

注解

这些函数提供 _strtime_wstrtime 的更安全的版本。 _strtime_s 函数将当前的本地时间复制到 buffer 所指向的缓冲区。 时间格式为 hh:mm:ss,其中 hh 是以 24 小时制表示小时的两位数,mm 是表示整点过的分钟数的两位数,ss 是表示秒的两位数。 例如,字符串 18:23:44 表示下午 6 点 23 分 44 秒。缓冲区必须至少为 9 个字节长;实际大小由第二个参数指定。

_wstrtime_s_strtime_s 的宽字符版本;_wstrtime_s 的参数和返回值都是宽字符字符串。 否则这些函数具有相同行为。

在 C++ 中,使用这些函数由模板重载简化;重载可以自动推导出缓冲区长度 (不再需要指定大小自变量),并且它们可以自动用以更新、更安全的对应物替换旧的、不安全的函数。 有关详细信息,请参阅安全模板重载

这些函数的调试库版本首先用 0xFE 填充缓冲区。 若要禁用此行为,请使用 _CrtSetDebugFillThreshold

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_tstrtime_s _strtime_s _strtime_s _wstrtime_s

要求

例程 必需的标头
_strtime_s <time.h>
_wstrtime_s <time.h> 或 <wchar.h>

有关兼容性的详细信息,请参阅 兼容性

示例

// strtime_s.c

#include <time.h>
#include <stdio.h>

int main()
{
    char tmpbuf[9];
    errno_t err;

    // Set time zone from TZ environment variable. If TZ is not set,
    // the operating system is queried to obtain the default value
    // for the variable.
    //
    _tzset();

    // Display operating system-style date and time.
    err = _strtime_s( tmpbuf, 9 );
    if (err)
    {
       printf("_strdate_s failed due to an invalid argument.");
      exit(1);
    }
    printf( "OS time:\t\t\t\t%s\n", tmpbuf );
    err = _strdate_s( tmpbuf, 9 );
    if (err)
    {
       printf("_strdate_s failed due to an invalid argument.");
       exit(1);
    }
    printf( "OS date:\t\t\t\t%s\n", tmpbuf );

}
OS time:            14:37:49
OS date:            04/25/03

另请参阅

工时管理
asctime_s_wasctime_s
ctime_s_ctime32_s_ctime64_s_wctime_s_wctime32_s_wctime64_s
gmtime_s_gmtime32_s_gmtime64_s
localtime_s_localtime32_s_localtime64_s
mktime_mktime32_mktime64
time_time32_time64
_tzset