【问题标题】:Problem appending text to file with system(), fgets and sprintf, in C在 C 中使用 system()、fgets 和 sprintf 将文本附加到文件时出现问题
【发布时间】: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' &gt;&gt; reports.log", comment, now()); 以避免未定义的行为。
  • 当然,这是一种愚蠢且可能不可移植的写入文件的方式。

标签: c windows command system


【解决方案1】:

这本书显然是在考虑类 Unix 系统的情况下编写的。 Windows cmd 不使用单引号,所以如下代码:

sprintf(cmd, "echo '%s %s' >> reports.log", comment, now());

应该改为使用双引号,像这样:

sprintf(cmd, "echo \"%s %s\" >> reports.log", comment, now());

【讨论】:

  • system的返回值可能表示错误。
猜你喜欢
  • 1970-01-01
  • 2021-06-25
  • 2019-11-12
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多