#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();