【发布时间】:2019-06-01 14:49:14
【问题描述】:
“Head First C”一书中的以下代码显然应该可以工作,但是(在 Windows 10 上)我只是将 comment 的内容打印出来,前面带有 `,并且没有编辑任何文件。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char* now()
{
time_t t;
time (&t);
return asctime(localtime (&t));
}
int main()
{
char comment[80];
char cmd[120];
fgets(comment, 80, stdin);
sprintf(cmd, "echo '%s %s' >> reports.log", comment, now());
system(cmd);
return 0;
}
【问题讨论】:
-
请在
system调用之前显示cmd的内容,例如:fputs(cmd, stdout). -
第一步是检查
localtime()、time()、asctime()、fgets()的函数返回值。是否符合预期?` -
2nd:
cmd[120]肯定不够大。尝试snprintf(cmd, sizeof cmd, "echo '%s %s' >> reports.log", comment, now());以避免未定义的行为。 -
当然,这是一种愚蠢且可能不可移植的写入文件的方式。