在窗口应用中使用printf,cout 等将输出重定向到console

#include <conio.h> #include <iostream> #include <io.h> #include <fcntl.h> #include <Windows.h> using namespace std ; int _tmain (int argc , _TCHAR * argv []) { AllocConsole (); // 为一个进程定位一个console ,如果是win32 程序的话这里就派上用场了 //Retrieves a handle to the specified standard device (standard input, standard output, or standard error). HANDLE hin = ::GetStdHandle (STD_INPUT_HANDLE ); HANDLE hout = ::GetStdHandle (STD_OUTPUT_HANDLE ); //Associates a C run-time file descriptor with an existing operating-system file handle. int hcin = _open_osfhandle ((intptr_t )hin ,_O_TEXT ); // 此时hcin 就成了一个file descriptor 了 // When a program opens a file, the operating system returns a corresponding file descriptor that the program refers to // in order to process the file. A file descriptor is a low positive integer. The first three file descriptors (0,1, and 2,) // are associated with the standard input (stdin), the standard output (stdout), and the standard error (stderr), respectively. // Thus, the function scanf() uses stdin and the function printf() uses stdout. You can override the default setting and // re-direct the process's I/O to different files by using different file descriptors: // #include <cstdio> // fprintf(stdout, "writing to stdout"); //write to stdout instead of a physical file FILE * fpin = _fdopen (hcin ,"r" ); *stdin = *fpin ; //stdin 就指向了文件指针 int hcout = _open_osfhandle ((intptr_t )hout ,_O_TEXT ); FILE * fpout = _fdopen (hcout ,"wt" ); *stdout = *fpout ; std ::ios_base ::sync_with_stdio (); // 将iostream 流同c runtime lib 的stdio 同步,标准是同步的 printf ("hello,world" ); std ::cout << "test" ; int i ; std ::cin >> i ; std ::cout << i ; return 0; }

鉴于以上的说明,这里可以在扩展一下,既然 *stdin = *fpin ;能够将stdin定向到文件指针,那么我同样可以实现将stdin,stdout重定向到文件的功能,并且只需做很少的改动:

#include "stdafx.h" #include <conio.h> #include <iostream> #include <io.h> #include <fcntl.h> #include <Windows.h> using namespace std ; int _tmain (int argc , _TCHAR * argv []) { AllocConsole (); // 为一个进程定位一个 console ,如果是 win32 程序的话这里就派上用场了 FILE * fpin = fopen ("c:\\in.txt" ,"r" ); *stdin = *fpin ; //stdin 就指向了文件指针 FILE * fpout = fopen ("c:\\out.txt" ,"wt" ); *stdout = *fpout ; std ::ios_base ::sync_with_stdio (); // 将 iostream 流同 c runtime lib 的 stdio 同步,标准是同步的 printf ("hello,world" ); std ::cout << "test" ; int i ; std ::cin >> i ; std ::cout << i ; return 0; }

有没有发现,如此产生的效果是惊人的!

FILE * fpin = fopen ("c:\\in.txt" ,"r" );
*stdin = *fpin ;

这两句将标准输入定位到了文件,当面临需要在控制台输入大量字符串,数字等的情况,例如输入变换矩阵什么的,此时使用这个就太方便了,直接将矩阵写入txt文件就可。

另一种简单的将stdin,out重定向的方法:

AllocaConsole(); freopen("CONIN$", "r+t", stdin); freopen("CONOUT$", "w+t", stdout); .... freeConsole();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值