win32 將控制台輸出重定向到txt文字上

2022-06-16 15:33:15 字數 1840 閱讀 4620

parent.cpp

#include #include 

intmain()

; se.nlength = sizeof

(security_attributes);

se.binherithandle = true

; se.lpsecuritydescriptor =null;

handle hfile = createfilew(l"

test.txt

", generic_write, file_share_read, &se, open_always, file_attribute_normal, 0

); bool ret =setstdhandle(std_output_handle, hfile);

printf(

"parent\n");

startupinfo si ={};

si.cb = sizeof

(startupinfo);

si.hstderror =getstdhandle(std_error_handle);

si.hstdoutput =getstdhandle(std_output_handle);

si.dwflags |=startf_usestdhandles;

process_information pi ={};

wchar cmd = l"child

.exe";

createprocessw(cmd, null,

0, 0, 1, 0, 0, 0, &si, &pi);

waitforsingleobject(pi.hprocess, infinite);

system(

"pause");

}

child.cpp

#include #include 

intmain()

else

return0;

}

如果控制台控制代碼被定向,getconsolemode函式將會返回0,並得到err 6的錯誤資訊,代表無效控制代碼。 

並且如果將writeconsole與重定向到檔案的標準控制代碼一起使用,則會失敗。

參考:writeconsole 

所以我們需要使用writefile來輸出,需要注意,如果沒有fflush(),會輸出

line 2 to file using

writefile.

line

4 to file using

writefile.

line

6 to file using

writefile.

line

8 to file using

writefile.

line

1 to file using

printf.

line

3 to file using

printf.

line

5 to file using

printf.

line

7 to file using printf.

會發現writefile先全部列印完,printf才開始列印。

因為當我們重定向到檔案時,輸出流將被會被完全緩衝

,除非使用fflush()

,否則將不會重新整理該流

,除非我們向其寫入大量資料。

參考: 

why does stdout need explicit flushing when redirected to file?

win32程式執行控制台命令並重定向輸出到檔案

shellexecute系列函式,可以執行控制台命令,但是無法實現輸出重定向。system函式,可以執行命令,並實現輸出重定向,但是無法隱藏控制台視窗。createprocess函式,則既可以執行命令,又可以實現輸出重定向,同時不顯示控制台視窗。但是,createprocess函式的使用顯得有些複雜...

控制台輸出重定向到Memo

函式runcmd void fastcall tform1 runcmd ansistring cmdline,tstrings result else createpipe hreadpipe,hwritepipe,null,1024 screen cursor crhourglass try d...

win32控制台 win32工程 MFC工程的區別

空專案 控制台 問2個問題即可。1.控制台 vs win32 mfc?嗯,有不有臉?有臉,選win32或mfc。沒有臉,選控制台。臉就是視窗,就是window.s 這個有臉 這個沒臉 控制台與win32 mfc 互動方式的不同,前者是cml 命令模式 後者是gui 使用者介面 2.mfc vs wi...