【问题标题】:Redirect output from function to File in C将输出从函数重定向到 C 中的文件
【发布时间】:2020-11-19 04:04:06
【问题描述】:

我想将一些 printf() 从函数重定向到文件。

我不想改变整个功能。相反,我想要这样的东西:

 void write_to_temp_File(struct s_28b_meta, struct s_db_entry);

file_name = "temp.txt";
handle_file = CreateFile(file_name, GENERIC_WRITE, 0,NULL, CREATE_ALWAYS, NULL);

//sanity check
if(handle_file == INVALID_HANDLE_VALUE)
printf("Could not open %s file, error %d\n", file_name, GetLastError());

//test check
test = GetHandleInformation(handle_file, lpdwFlags);
printf("The return value is %d, error %d\n", test, GetLastError());

//actually print into file
fprintf(handle_file, reader_print_db(byte **ptr_to_s_20b_parse_entries, 1024));

//clean close and exit
CloseHandle(handle_file);
return 0;

所以实际上,我想打开一个文件并将函数内所有打印的输出重定向到新创建的文件。

在 sysCall 中会是这样的:

text.exe > temp.txt

有什么好的方法吗?如何获得函数输出的长度,而不是像我这样的静态值?

谢谢你

【问题讨论】:

  • 这与minimal reproducible example 相差甚远...我不明白[f]printf 是否在函数内部,或者您是否想将函数返回的内容写入文件,而不是如果你想写一个字符串或一堆单独的值。
  • 您可以在函数中使用fprintf 并传递stdout 或其他文件指针。 printffprintf 都返回写入的字节数。
  • 一些 printf() 打电话但不是其他人?重写整个函数来做你想做的事。
  • 我明白你们的意思,但我在这里尝试做一些解决方法。

标签: c file redirect output


【解决方案1】:

使用 freopen 应该会对您有所帮助。

freopen("temp.txt", "a+", stdout);

使用 freopen() 重新打开标准输出后,所有输出语句 printf, putchar 都将重定向到文件 temp.txt。因此,此后任何printf() 语句都会将其输出重定向到temp.txt 文件。

参考: https://linux.die.net/man/3/freopen

【讨论】:

  • 现在,恢复原来的stdout 流,用于相关函数之后运行的代码。
  • 感谢您的提示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
相关资源
最近更新 更多