如何用C/C++获得冲制台程序打印的字符串

hyq1986 2005-07-25 10:39:46
写C/C++程序,如何才能在调用外部控制台程序的同时获得这些程序的用户返回信息?

如给一个控制台程序做GUI辅助程序

谢谢!
...全文
120 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hyq1986 2005-07-27
  • 打赏
  • 举报
回复
原来涉及进程间通讯
boxban 2005-07-25
  • 打赏
  • 举报
回复
Keywords: _pipe, _spawnvp, _dup2
Example 2

// This is a simple filter application. It will spawn
// the application on command line. But before spawning
// the application, it will create a pipe that will direct the
// spawned application's stdout to the filter. The filter
// will remove ASCII 7 (beep) characters.

// Beeper.Cpp

/* Compile options needed: None */
#include <stdio.h>
#include <string.h>

int main()
{
int i;
for(i=0;i<100;++i)
{
printf("\nThis is speaker beep number %d... \n\7", i+1);
}
return 0;
}


// BeepFilter.Cpp
/* Compile options needed: none
Execute as: BeepFilter.exe <path>Beeper.exe
*/
#include <windows.h>
#include <process.h>
#include <memory.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>

#define OUT_BUFF_SIZE 512
#define READ_HANDLE 0
#define WRITE_HANDLE 1
#define BEEP_CHAR 7

char szBuffer[OUT_BUFF_SIZE];

int Filter(char* szBuff, ULONG nSize, int nChar)
{
char* szPos = szBuff + nSize -1;
char* szEnd = szPos;
int nRet = nSize;

while (szPos > szBuff)
{
if (*szPos == nChar)
{
memmove(szPos, szPos+1, szEnd - szPos);
--nRet;
}
--szPos;
}
return nRet;
}

int main(int argc, char** argv)
{
int nExitCode = STILL_ACTIVE;
if (argc >= 2)
{
HANDLE hProcess;
int hStdOut;
int hStdOutPipe[2];

// Create the pipe
if(_pipe(hStdOutPipe, 512, O_BINARY | O_NOINHERIT) == -1)
return 1;

// Duplicate stdout handle (next line will close original)
hStdOut = _dup(_fileno(stdout));

// Duplicate write end of pipe to stdout handle
if(_dup2(hStdOutPipe[WRITE_HANDLE], _fileno(stdout)) != 0)
return 2;

// Close original write end of pipe
close(hStdOutPipe[WRITE_HANDLE]);

// Spawn process
hProcess = (HANDLE)spawnvp(P_NOWAIT, argv[1],
(const char* const*)&argv[1]);

// Duplicate copy of original stdout back into stdout
if(_dup2(hStdOut, _fileno(stdout)) != 0)
return 3;

// Close duplicate copy of original stdout
close(hStdOut);

if(hProcess)
{
int nOutRead;
while (nExitCode == STILL_ACTIVE)
{
nOutRead = read(hStdOutPipe[READ_HANDLE],
szBuffer, OUT_BUFF_SIZE);
if(nOutRead)
{
nOutRead = Filter(szBuffer, nOutRead, BEEP_CHAR);
fwrite(szBuffer, 1, nOutRead, stdout);
}

if(!GetExitCodeProcess(hProcess,(unsigned long*)&nExitCode))
return 4;
}
}
}

printf("\nPress \'ENTER\' key to continue... ");
getchar();
return nExitCode;
}

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧