Reputation: 3930
I want to get current time (without a current date) in C. The main problem is when I want to do it with functions. When I dont use them, evertyhing is just fine. Can anybody tell me, why my code shows only an hour? (take a look at the attached image). Thanks in advance.
#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;
}
Upvotes: 1
Views: 4236
Reputation: 9
In getting the time, you can try this one:
#include <stdio.h>
int main(void)
{
printf("Time: %s\n", __TIME__);
return 0;
}
Result:
Time: 10:49:49
Upvotes: 0
Reputation: 2007
The sizeof
operator returns the length of the variable str_time
which is a pointer to char. It doesn't returns the length of your dynamic array.
Replace sizeof(str_time)
by 100
and it will go fine.
Upvotes: 4
Reputation: 3020
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 :)
Upvotes: 0
Reputation: 8853
try this...
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Upvotes: 0
Reputation: 42165
sizeof(str_time)
gives you the size of char*
. You want the size of the buffer str_time
points to instead. Try
strftime(str_time, 100, "%H:%M:%S", tm);
// ^ size of buffer allocated for str_time
Other minor points - you should include <stdlib.h>
to pick up a definition of malloc
and should free(t)
after printing its content in main
.
Upvotes: 7