日期:2014-05-16  浏览次数:20686 次

linux 时间编程问题
在下最近在写一个有关与时间的程序,如下:

/*
 * 获得本地时间
 * 返回字符串格式"年_月_日"
 */
char *get_local_time_y_m_d()
{
time_t *the_time;
struct tm tm_ymd;
char *buf;
the_time=(time_t *)malloc(sizeof(time_t));
//tm_ymd=(struct tm *)malloc(sizeof(struct tm));
buf=(char *)malloc(sizeof(char)*16);
memset(buf,'\0',sizeof(char)*16);

//printf("%p\n%p\n",the_time,tm_ptr);

time(the_time);
//tm_ymd=gmtime(the_time);
localtime_r(the_time,&tm_ymd);
//memcpy(tm_ymd,localtime(the_time),sizeof(struct tm));
strftime(buf,16,"%Y_%m_%d",&tm_ymd);
free(the_time);
/*
 * 看样子struct tm 结构似乎不能free
 */
//free(tm_ptr);
return buf;
}
/*
 * 获得本地时间
 * 返回字符串格式"时_分_秒"
 */
char *get_local_time_h_m_s()
{
time_t *the_time;
struct tm tm_hms;
char *buf;
the_time=(time_t *)malloc(sizeof(time_t));
//tm_hms=(struct tm *)malloc(sizeof(struct tm));
buf=(char *)malloc(sizeof(char)*16);
memset(buf,'\0',sizeof(char)*16);

//printf("%p\n%p\n",the_time,tm_ptr);

time(the_time);
//tm_hms=gmtime(the_time);
localtime_r(the_time,&tm_hms);
//memcpy(tm_hms,localtime(the_time),sizeof(struct tm));
strftime(buf,16,"%H:%M:%S",&tm_hms);
free(the_time);
/*
 * 看样子struct tm 结构似乎不能free
 */
//free(tm_ptr);
return buf;
}

这两个函数在程序中会经常调用,但是不论先调用了那个函数,在调用另一个的时候,程序立马错误推出。在网上查了查,是由于localtime和gmtime重复调用问题。在下想请问下各位,有没有什么能随时获得系统时间的方法,C语言
------解决方案--------------------
我看了,改了一下,不知道 改没有改变你的意思:
#include <time.h>                                                                                                                     
#include <stdio.h>                                                                                                                    
#include <string.h>