Please bear with me since I'm still really new to C programming. When I run this code:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
while (1) {
time_t mytime;
mytime = time(NULL);
printf("%s Hello world\n", ctime(&mytime));
sleep(1);
}
return 0;
}
The output always looks like this:
Wed Jan 18 02:32:32 2017
Hello world
Wed Jan 18 02:32:33 2017
Hello world
Wed Jan 18 02:32:34 2017
Hello world
What I want is like this:
Wed Jan 18 02:32:32 2017 Hello world
Wed Jan 18 02:32:33 2017 Hello world
Wed Jan 18 02:32:34 2017 Hello world
How can I do that ?
Note:
If I remove \n
from printf("%s Hello world\n", ctime(&mytime));
it'll result like this:
Wed Jan 18 02:38:29 2017
Hello worldWed Jan 18 02:38:30 2017
Hello worldWed Jan 18 02:38:31 2017
Hello worldWed Jan 18 02:38:32 2017
Hello worldWed Jan 18 02:38:33 2017
The ctime
function will return a pointer to a string which ends in a newline.
From the man page:
The call
ctime(t)
is equivalent toasctime(localtime(t))
. It converts the calendar time t into a null-terminated string of the form "Wed Jun 30 21:49:08 1993\n"
If you don't want the newline, you need to save the pointer and remove the newline before printing.
char *t = ctime(&mytime);
if (t[strlen(t)-1] == '\n') t[strlen(t)-1] = '\0';
printf("%s Hello world\n", t);
Use strftime
to format your own string:
#include <stdio.h>
#include <time.h>
int main(void)
{
char buf[100];
strftime(buf, 100, "%a %b %d %T %Y", localtime(&(time_t){time(NULL)}));
printf("%s Hello world\n", buf);
}
For simple formatting tasks like the one in the question, you can spare yourself the printf
and let strftime
do all the work:
strftime(buf, 100, "%a %b %d %T %Y Hello world\n",
localtime(&(time_t){time(NULL)}));
fputs(buf, stdout);
You should also check the return value of strftime
, zero may indicate failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With