今天在学习的时候遇到strftime编译报错的情况,我报的警告为不能把strftime返回的整型赋值给指针类型char *,但经过查阅strftime的返回类型的确是char *,后来书中写到一个错误的解决方法是在头文件定义之前加一个宏定义(具体原因为GNU库在默认情况下并未声明strptime函数,要解决这个问题,需要请求使用X/Open标准功能,这需要在包含time.h头文件之前加上一个宏定义) 宏定义为#define _XOPEN_SOURCE
附上一个练习代码:
#define _XOPEN_SOURCE
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
struct tm *tm_ptr,timestruct;
time_t the_time;
char buf[256];
char *result;
(void)time(&the_time);
tm_ptr=localtime(&the_time);
strftime(buf,256,"%A %d %B, %I:%S %p",tm_ptr);
printf("strftime gives %s\n",buf);
strcpy(buf,"Thu 26 July 2007,17:53 will do fine");
printf("calling strptime with: %s\n",buf);
tm_ptr=×truct;
result=strptime(buf,"%a %d %b %Y,%R",tm_ptr);
printf("strptime consumed up to: %s\n",result);
printf("strptime gives:\n");
printf("date: %02d/%02d/%02d\n",tm_ptr->tm_year%100,tm_ptr->tm_mon+1,tm_ptr->tm_mday);
printf("time: %02d:%02d\n",tm_ptr->tm_hour,tm_ptr->tm_min);
exit(0);
}