2013-04-11 135 views
1

我想在C中获得当前时间(不包括当前日期)。主要问题是当我想用函数来完成时。当我不使用它们时,evertyhing就很好。有人可以告诉我,为什么我的代码只显示一个小时? (看看附图)。提前致谢。以C获取当前时间,功能

#include <stdio.h> 
#include <time.h> 
#include <string.h> 

char* get_time_string() 
{ 
    struct tm *tm; 
    time_t t; 
    char *str_time = (char *) malloc(100*sizeof(char)); 
    t = time(NULL); 
    tm = localtime(&t); 
    strftime(str_time, sizeof(str_time), "%H:%M:%S", tm); 
    return str_time; 
} 

int main(int argc, char **argv) 
{ 
    char *t = get_time_string(); 
    printf("%s\n", t); 
    return 0; 
} 

enter image description here

+3

提示:检查什么'sizeof(str_time)'返回。 – Joulukuusi 2013-04-11 09:08:28

+2

不要忘记当你完成它时释放你的字符串...... – Alnitak 2013-04-11 09:14:09

+1

在不同的注释中,1)'sizeof(char)== 1'根据定义,你应该删除乘法,2)你没有检查分配是否成功。 – 2013-04-11 09:16:02

回答

4

sizeof操作者返回变量str_time的长度,该长度为char一个指针。它不会返回动态数组的长度。

替换通过100它会很好。

+0

谢谢,工作!:) – yak 2013-04-11 09:11:33

+0

接受答案然后:) – 2013-04-11 09:12:56

+1

'sizeof'不是一个函数。这是一个运营商。 – 2013-04-11 10:28:42

6

给你的尺寸为char*。你想要缓冲区大小的str_time来代替。尝试

strftime(str_time, 100, "%H:%M:%S", tm); 
//    ^size of buffer allocated for str_time 

其他小点 - 在main打印的内容后,你应该包括<stdlib.h>回暖的malloc定义和应该free(t)

1

试试这个...

int main() 
{ 
    time_t rawtime; 
    struct tm * timeinfo; 

    time (&rawtime); 
    timeinfo = localtime (&rawtime); 
    printf ("Current local time and date: %s", asctime (timeinfo)); 

    return 0; 
} 
+0

它不是一个功能... – yak 2013-04-11 09:12:36

+0

@yak:只需用这个替换你的主...它应该工作 – 2013-04-11 09:14:09

1

运用这种概念获取系统时间和更新它。多年前我已经在我的项目中使用了它。您可以根据您的要求进行更改。

updtime()     /* FUNCTION FOR UPDATION OF TIME */ 
{ 
struct time tt; 
char str[3]; 
gettime(&tt); 
itoa(tt.ti_hour,str,10); 
setfillstyle(1,7); 
bar(getmaxx()-70,getmaxy()-18,getmaxx()-30,getmaxy()-10); 
setcolor(0); 
outtextxy(getmaxx()-70,getmaxy()-18,str); 
outtextxy(getmaxx()-55,getmaxy()-18,":"); 
itoa(tt.ti_min,str,10); 
outtextxy(getmaxx()-45,getmaxy()-18,str); 
return(0); 
} 
The previous function will update time whenever you will call it like 

and this will give you time 

int temp; 
struct time tt; 
gettime(&tt);      /*Get current time*/ 
temp = tt.ti_min; 

如果您想更新时间,您可以使用下面的代码。

gettime(&tt); 
    if(tt.ti_min != temp) /*Check for any time update */ 
    { 
    temp = tt.ti_min; 
    updtime(); 
    } 

这是复杂的代码,但如果你理解它,那么它将解决你所有的问题。

享受:)

1

在得到的时候,你可以试试这个:

#include <stdio.h> 

int main(void) 
{ 
    printf("Time: %s\n", __TIME__); 
    return 0; 
} 

结果:

时间:十点49分49秒