这是我用于将内容打印到名为 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)
最佳答案
解决打印到终端并将输出保存到文件的方法
- 使用
printf()
或fprintf(stdin, "");
到标准输入,在fprintf();
之后的语句 >
- 写入文件后使用
system("cat output.log");
(适用于Linux)。 - 使用函数在写入后打印文件
#include <stdio.h>
void printFile(FILE *fp) {
char line[2048];
while (fscanf(fp, "%[^\n]s", line) == 1) {
printf("%s\n", line);
fgetc(fp); // OR fseek(fp, 1, 1); To throw away the new line in the input
// buffer
}
}
int main() {
FILE *fp;
fp = fopen("a.txt", "r");
if (fp == NULL) {
printf("Error opening the file\n");
return 1;
}
printFile(fp);
return 0;
}
- 使用 Linux shell
./a.out | tee输出.log
并在 C 代码中使用普通的 printf() 语句。
关于c - 如何在 C 中在终端上显示输出并同时保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52791185/