在某些時(shí)候,我們可能需要在Win32窗口應(yīng)用程序中打開控制臺(tái)窗口,打印一些消息,或者作為當(dāng)前程序的另外一個(gè)人機(jī)交互界面,或者為了幫助調(diào)試程序。為了達(dá)到這種效果,需要了解函數(shù)AllocConsole和C-Runtime的freopen函數(shù)。
AllocConsole函數(shù)會(huì)為當(dāng)前的窗口程序申請(qǐng)一個(gè)Console窗口。這是MSDN上對(duì)AllocConsole的介紹:
AllocConsole
The AllocConsole function allocates a new console for the calling process.
BOOL AllocConsole(void);
函數(shù)調(diào)用成功,返回非零值,調(diào)用不成功則返回0.
在為當(dāng)前窗口程序申請(qǐng)到console后,我們需要調(diào)用C-Runtime的freopen函數(shù)將標(biāo)準(zhǔn)輸出(stdout)重定位到新申請(qǐng)的console。
freopen的原型如下:
FILE *freopen(
const char *path,
const char *mode,
FILE *stream
);
我們調(diào)用的時(shí)候是這么著傳入?yún)?shù)的:
freopen("CONOUT$","w",stdout);
其中"CONOUT$"是指代當(dāng)前console的特殊字符串,"w"表明以written模式打開這個(gè)console,stdout指代的是系統(tǒng)的標(biāo)準(zhǔn)輸出設(shè)備。
下面是整個(gè)的代碼:
if(AllocConsole())

{
freopen("CONOUT$","w",stdout);
printf("hello, world!");
}