简体   繁体   English

将 output 从 function 重定向到 C 中的文件

[英]Redirect output from function to File in C

I want to redirect some printf() from a function to a file.我想将一些 printf() 从 function 重定向到文件。

I dont want to change the whole function.我不想改变整个 function。 Instead I want something like this:相反,我想要这样的东西:

 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;

So in fact, I want to open a file and redirect the output of all prints inside the function to the new created file.所以实际上,我想打开一个文件并将 function 内所有打印的 output 重定向到新创建的文件。

In sysCall it would be something like:在 sysCall 中会是这样的:

text.exe > temp.txt

Is there a good way to do it and how can I get the length of the output of the function, instead of a static value like I have?有没有一种好的方法,我怎样才能得到 function 的 output 的长度,而不是像我这样的 static 值?

Thank you already谢谢你

using freopen should help you.使用 freopen 应该可以帮助你。

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

After reopening the stdout with freopen() all output statement printf, putchar are redirected to file temp.txt .使用 freopen() 所有 output 语句printf, putchar被重定向到文件temp.txt So after that any printf() statement will redirect it's output to the temp.txt file.因此,此后任何printf()语句都会将其 output 重定向到temp.txt文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM