我是靠谱客的博主 清新香氛,最近开发中收集的这篇文章主要介绍"undefined reference to strptime"之自己定义strptime函数简单介绍实现測试,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
简单介绍
strptime()函数可以依照特定时间格式将字符串转换为时间类型。简单点说可以将字符串时间转化为时间戳。
这个函数包括在time.h头文件里,在Unix或者类Unix系统中,我们会常常接触到。可是到了跑Nuttx系统的Pixhawk。真是醉了,非常多东西都没有,或者少了非常多东西,比方time.h中就没有这个函数的实现,又如dirent.h中的一些文件类型的宏定义也没有了。
可是我们非常须要,比方在时间的比較上,我们不能去拿字符串去操作来比較。会搞死人的。直接得到时间戳,三下两除二就搞定了。那就要用到strptime这个函数了。
实现
mystrptime.c
/*
* Note:因time.h中没有strptime函数(UNIX中是有的),本文件是对strptime功能的自己定义实现;
* We do not implement alternate representations. However, we always
* check whether a given modifier is allowed for a certain conversion.
*/
#include "mystrptime.h"
static const char *day[7] = {
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
};
static const char *abday[7] = {
"Sun","Mon","Tue","Wed","Thu","Fri","Sat"
};
static const char *mon[12] = {
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
};
static const char *abmon[12] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static const char *am_pm[2] = {
"AM", "PM"
};
static int conv_num(const char **buf, int *dest, int llim, int ulim)
{
int result = 0;
/* The limit also determines the number of valid digits. */
int rulim = ulim;
if (**buf < '0' || **buf > '9')
return (0);
do {
result *= 10;
result += *(*buf)++ - '0';
rulim /= 10;
} while ((result * 10 <= ulim) && rulim && **buf >= '0' && **buf <= '9');
if (result < llim || result > ulim)
return (0);
*dest = result;
return (1);
}
char * mystrptime(const char *buf, const char *fmt, struct tm *tm)
{
char c;
const char *bp;
size_t len = 0;
int alt_format, i, split_year = 0;
bp = buf;
while ((c = *fmt) != '