曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 6660|回复: 0
打印 上一主题 下一主题

strptime()

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-2-21 12:16:50 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
为了帮助更好的读取日期,可以应用 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 = &timestruct;
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 即可。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-9 20:46 , Processed in 0.079422 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表