簡體   English   中英

將 output 從 function 重定向到 C 中的文件

[英]Redirect output from function to File in C

我想將一些 printf() 從 function 重定向到文件。

我不想改變整個 function。 相反,我想要這樣的東西:

 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;

所以實際上,我想打開一個文件並將 function 內所有打印的 output 重定向到新創建的文件。

在 sysCall 中會是這樣的:

text.exe > temp.txt

有沒有一種好的方法,我怎樣才能得到 function 的 output 的長度,而不是像我這樣的 static 值?

謝謝你

使用 freopen 應該可以幫助你。

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

使用 freopen() 所有 output 語句printf, putchar被重定向到文件temp.txt 因此,此后任何printf()語句都會將其 output 重定向到temp.txt文件。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM