我想使用asctime()
在C语言中打印时间,但是当文本被打印出时,在timeString
之后会附加随机字符。另外,在日志文件中打印出的文本syslog()
与在shell中打印出的文本printf()
不同。在代码下,我提供了两个输出的确切输出。如何摆脱这种行为?该代码在RaspberryPi上运行,并且我已通过默认的macOS终端登录。
time_t rawTime;
time(&rawTime);
struct tm timeInfo = *gmtime(&rawTime);
// ...
char *log;
char *timeString = strdup(asctime(&timeInfo));
asprintf(&log, "UTC: %s %.*s Last status: %s. New status: %s.",
timeString, 5, " ", "Hello", "World");
openlog("httpd-status-notifier", LOG_PID, LOG_USER);
syslog(logLevel, "%s", log);
printf("%s\n", log);
// ...
Syslog:
Dec 22 17:18:17 rasp httpd-status-notifier[25458]: UTC: Sun Dec 22 17:18:17 2019#012 Last status: Hello. New status: World.
(这里syslog
产生#012
)
Shell(printf):
UTC: Sun Dec 22 17:18:17 2019
Last status: Hello. New status: World.
((printf
在此处产生换行符)
顺便说一句,是的,我确实注意到syslog
已经记录了日期。
问题是asctime()
产生一个换行符,并在日志文件中将其表示为八进制ASCII值012
,如@mangusta在注释部分中指出的那样。因此,修剪字符串可以解决问题。