【发布时间】:2018-10-13 08:46:41
【问题描述】:
这是我用于将内容打印到名为 output.log 的文件的代码:
FILE *openFile(void)
{
FILE *entry;
entry = fopen("output.log", "a");
if (entry != NULL)/*verifying whether it opened*/
{/*printing the --- separator*/
fprintf(entry, "---\n");/*unable to write to unopened file*/
}
return entry;
}
void writeFile(FILE *entry, char *category, double formerX, double
formerY, double latestX, double latestY)
{
/*writing an entry to the given file, as told in the given
document*/
fprintf(entry, "%4s (%7.3f, %7.3f)-(%7.3f, %7.3f) \n", category,
formerX, formerY, latestX, latestY);
}
/*closing the file and checking for errors*/
void closeFile(FILE *entry)
{
if (ferror(entry))
{
perror("Error, can't write to the file");
}
fclose(entry);
}
我现在想在终端屏幕上打印相同的内容(保存在 output.log 中)。如何添加此功能?
这是 output.log 的一部分:
MOVE ( 0.000, 0.000)-( 18.000, -0.000)
DRAW ( 18.000, -0.000)-( 19.000, -0.000)
DRAW ( 19.000, -0.000)-( 20.000, -0.000)
DRAW ( 20.000, -0.000)-( 21.000, -0.000)
DRAW ( 21.000, -0.000)-( 22.000, -0.000)
DRAW ( 22.000, -0.000)-( 23.000, -0.000)
DRAW ( 23.000, -0.000)-( 25.000, -0.000)
MOVE ( 25.000, -0.000)-( 0.000, -0.000)
MOVE ( 0.000, -0.000)-( -0.000, 1.000)
MOVE ( -0.000, 1.000)-( 18.000, 1.000)
DRAW ( 18.000, 1.000)-( 19.000, 1.000)
【问题讨论】:
-
您可以先使用
sprintf将数据格式化到缓冲区中,然后通过printf和fprintf输出。 -
使用 shell 工具,您可以在另一个 shell 上使用
tail -f output.log,或者如果您的程序只打印到stdout,您可以使用myprog | tee output.log -
@Gerhardh 在这种情况下,他将使用正确设置的
malloc,也许snprintf。 -
@Amessihel 可能的值似乎非常有限。在这里,一个固定大小的缓冲区就足够了。
-
@Amessihel 它工作正常,但我的图形搞砸了,所以我需要将 printf 输出重定向到另一个终端窗口。我怎样才能做到这一点?本质上,日志条目应该被打印到标准错误。