1

我想在 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;
}

在此处输入图像描述

4

5 回答 5

7

sizeof(str_time)给你的大小char*。您希望缓冲区的大小str_time改为。尝试

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

其他次要要点 - 您应该包括在<stdlib.h>将其内容打印到.mallocfree(t)main

于 2013-04-11T09:10:40.163 回答
4

运算符返回变量的sizeof长度,该变量str_time是指向 char 的指针。它不返回动态数组的长度。

替换sizeof(str_time)100,它会好起来的。

于 2013-04-11T09:10:26.470 回答
0

Use This Concept Getting System Time and Updating it. I have used this in my project many years before. you can change it as per your requirements.

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;

If you want to update time the you can use the following code.

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

This is complex code but if you understand it then it will solve your all problems.

Enjoy :)

于 2013-04-11T09:16:30.750 回答
0

尝试这个...

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

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

  return 0;
}
于 2013-04-11T09:11:50.867 回答
0

有时间的话,你可以试试这个:

#include <stdio.h>

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

结果:

时间:10:49:49

于 2016-09-02T02:56:35.300 回答