|
-
April 8th, 2026, 11:25 AM
#1
Simple time program won't show time
Is there any reason this code snippet won't do what it's supposed to do?
I'm learning socket programming and there's a simple program that tells the time but I think MSVC isn't building this code because of deprecated code.
Code:
#include <stdio.h>
#include <time.h>
int main() {
time_t timer;
time(&timer);
char buf[26];
printf_s("Local time is: %d", ctime_s(buf,sizeof(buf), &timer));
return 0;
}
When I run this code all I get is this....
How do i get this to show the time from my computer?
-
April 8th, 2026, 11:44 AM
#2
Re: Simple time program won't show time
https://en.cppreference.com/w/c/chrono/ctime
ctime_s returns an error code, not a string.
Maybe something like
Code:
if ( ctime_s(buf,sizeof(buf), &timer) == 0 ) {
printf_s("Local time is: %s", buf);
}
-
April 9th, 2026, 02:01 PM
#3
Re: Simple time program won't show time
The return value of ctime_s is of type errno_t not a string
Code:
errno_t err = ctime_s(buf, sizeof(buf), &timer);
if (err == 0)
printf_s("Local time is: %s", buf);
-
Re: Simple time program won't show time
As already said before, ctime_s function returns 0 (zero) in case of success. So it's no wonder what your program prints. Modify it as follows:
Code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer;
time(&timer);
char buf[26];
ctime_s(buf, sizeof(buf), &timer);
printf_s("Local time is: %s", buf);
return 0;
}
Additional note:
ctime returns a pointer to static data and is not thread-safe. In addition, it modifies the static tm object which may be shared with gmtime and localtime. POSIX marks this function obsolete and recommends strftime instead. The C standard also recommends strftime, which is safer and more flexible.
Code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t timer = { 0 };
time(&timer);
char buf[26] = { '\0' };
struct tm localTime = { 0 };
localtime_s(&localTime, &timer);
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &localTime);
printf_s("Local time is: %s\n", buf);
return 0;
}
See also:
Last edited by ovidiucucu; Today at 01:30 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|