输入输出重定向
本文解释如何重新从 C 程序, 定向到文件 stdout 再恢复原始 stdout 同一程序中稍后。 C 函数通常用于重定向 stdout 或 stdin 是 freopen()。 将 stdout 重定向到文件称为 FILE.TXT, 使用以下调用:
freopen( "file.txt", "w", stdout );
该语句导致所有后续输出, 向 stdout, 它通常定向到转到 FILE.TXT 文件。
要返回到显示 (默认 stdout), stdout 使用以下调用:
要返回到显示 (默认 stdout), stdout 使用以下调用:
freopen( "CON", "w", stdout );
在两个情况, 检查返回值是 freopen() 以确保重定向到实际发生。
下面是一个短程序来演示是 stdout 重定向:
下面是一个短程序来演示是 stdout 重定向:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *stream ;
if((stream = freopen("file.txt", "w", stdout)) == NULL)
exit(-1);
printf("this is stdout output\n");
stream = freopen("CON", "w", stdout);
printf("And now back to the console once again\n");
}
#include <stdlib.h>
void main(void)
{
FILE *stream ;
if((stream = freopen("file.txt", "w", stdout)) == NULL)
exit(-1);
printf("this is stdout output\n");
stream = freopen("CON", "w", stdout);
printf("And now back to the console once again\n");
}
BOOL CDnsTestDlg::My_System(char *cmd,CString& m_strOutPut)
{
SECURITY_ATTRIBUTES lsa;
STARTUPINFO si;
PROCESS_INFORMATION pi, *lppi;
HANDLE hReadPipe, hWritePipe;
lsa.nLength = sizeof(SECURITY_ATTRIBUTES);
lsa.lpSecurityDescriptor = NULL;
lsa.bInheritHandle = TRUE;
lppi = π
CWaitCursor waitCursor;
if(!CreatePipe(&hReadPipe, &hWritePipe, &lsa, 0)) {
AfxMessageBox("Error on create pipe.");
return FALSE;
}
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
if(!CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
AfxMessageBox("Error on create process");
return FALSE;
}
DWORD cchReadBuffer;
CString strText;
TCHAR ph[5000];
m_strOutPut.Empty();
for(;;) {
cchReadBuffer = 0;
if(!PeekNamedPipe(hReadPipe, ph, 1, &cchReadBuffer, NULL, NULL)) break;
if(cchReadBuffer) {
if(!ReadFile(hReadPipe, ph, 4096, &cchReadBuffer, NULL)) break;
ph[cchReadBuffer] = 0;
m_strOutPut += ph;;
}
else
if(WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0) break;
Sleep(500);
}
ph[cchReadBuffer] = 0;
m_strOutPut += ph;
CloseHandle(hReadPipe);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(hWritePipe);
return TRUE;
}