|
为了帮助更好的读取日期,可以应用 strptime()函数,它使用表示日期和世界的字符串并创建一个表示日期和时间的 tm 结构体。
所以说,它算是一个 strftime() 函数的反函数。
函数原型及定义如下:
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *timeptr);
format 参数里的时间表示格式和 strftime() 函数中的一样。
strptime() 和 sscanf() 函数工作原理类似,它会扫描字符串,查找可识别的域,并把它们写进变量。填充进 tm 结构体中的成员取决于 format 参数字符串。但是,strptime()中的转换说明符相对于 strftime() 函数中的相对要求要宽松些,因为 strptime() 允许有日期和月份有简写和全名两种形式存在。这两种表示在 sprptime() 中都能匹配 %a 转换说明符。还有,strftime() 对于小于 10 的数的总是使用 0 引导符(如 1 要表示为 01),strptime() 则视为可选。
strptime() 返回一个指针,这个指针指向最后一个被转换内容的后面一个字符处。如果它遇到无法转换的字符,转换就会简单的在那里停止。调用程序需要充分的检查已经转换的字符串以确保这些有效的转换值已经写进 tm 结构体中。
strftime() 和 strptime() 测试代码:
01 #include <time.h>
02 #include <stdio.h>
03 #include <stdlib.h>
04 #include <string.h>
05
06 int main()
07 {
08 struct tm *tm_ptr, timestruct;
09 time_t the_time;
10 char buf[256];
11 char *result;
12
13 (void)time(&the_time);
14 tm_ptr = localtime(&the_time);
15 strftime(buf, 256, "%A %d %B, %I:%S %p", tm_ptr);
16
17 printf("strftime gives: %s\n", buf);
18
19 strcpy(buf,"Thu 26 July 2007, 17:53 will do fine");
20
21 printf("calling strptime with: %s\n", buf);
22 tm_ptr = ×truct;
23 /*----------------strptime()应用------------------------------*/
24 result = strptime(buf, "%a %d %b %Y, %R", tm_ptr);
25 printf("strptime consumed up to: %s\n", result);
26
27 printf("strptime gives:\n");
28 printf("date: %02d/%02d/%02d\n",
29 tm_ptr->tm_year % 100,
30 tm_ptr->tm_mon+1,
31 tm_ptr->tm_mday);
32
33 printf("time: %02d:%02d\n",tm_ptr->tm_hour, tm_ptr->tm_min);
34
35 exit(0);
36 } 运行及输出:[root@localhost C]# ./strftime.exe
strftime gives: Saturday 21 February, 12:05 PM
calling strptime with: Thu 26 July 2007, 17:53 will do fine
strptime consumed up to: will do fine
strptime gives:
date: 07/07/26
time: 17:53
说明:
需要传递给 strptime() 的进行扫描转换的字符串放在 buf 数组中(其中 will do fine 不是日期或时间格式,故无法进行转换);在进行转换后,被转换的各个日期时间值都存储在 tm 类型的结构体 structtime 中,tm_ptr 为 tm 类型的结构体指针。
%R 为 %H:%M 的简写
在编译过程中,会发现一个警告:strftime.c: In function ‘main’:
strftime.c:26: warning: assignment makes pointer from integer without a cast
这是因为,GNU 库在默认情况下并不声明 strptime() 函数。为了修正这个问题,需要明确的要求使用 X/Open 标准,那么可以通过在包含 time.h 头文件前添加 #define _XOPEN_SOURCE 即可。 |
|