CBuilder中使用管道技術例項 (轉)

worldblog發表於2008-01-21
CBuilder中使用管道技術例項 (轉)[@more@]

廢話不多說,大家來看程式碼

bool __fastcall TForm1::RunCmd(AnsiString cmd,TStringList *stringlist)
{
  TMemoryStream *memstream=new TMemoryStream();
  AnsiString rn="";
  PROCESS_INFORMATION proc;
  STARTUPINFO start;
  SECURITY_ATTRIBUTES sa;
  long ret;
  unsigned long lngBytesread;
  HANDLE hReadPipe,hWritePipe;
  char *strBuff=(char *)malloc(256);
  if(strBuff==NULL)
  {
  return false;
  }
  sa.nLength = sizeof(SECURITY_ATTRIBUTES);
  sa.bInheritHandle=true;
  sa.lpSecurityDescriptor=NULL;
  ret=CreatePipe(&hReadPipe,&hWritePipe,&sa,0);
  if(ret==0)
  {
  //建立管道失敗
  return false;
  }
  memset(&start,0x00,sizeof(STARTUPINFO));
  start.cb=sizeof(STARTUPINFO);
  start.dwFlags=STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  start.hStdOutput=hWritePipe;
  start.hStdError=hWritePipe;
  bool retc=CreateProcess(NULL,cmd.c_str(),NULL,NULL,true, 0, 0, NULL, &start, &proc);
  if(!retc)
  {
  return false;
  }
  CloseHandle(hWritePipe);
  unsigned long len;
  memstream->Position=0;
  while(true)
  {
  memset(strBuff,0x00,256);
  GetFileSize(hReadPipe,&len);
  ret = ReadFile(hReadPipe, strBuff, 256, &lngBytesread,NULL);
  if(ret==0)
  {
  break;
  }
  else
  {
  memstream->Write(strBuff,lngBytesread);
  }
  }
  CloseHandle(proc.hProcess);
  CloseHandle(proc.hThread);
  CloseHandle(hReadPipe);
  memstream->Position=0;
  free(strBuff);
  stringlist->LoadFromStream(memstream);
  memstream->Clear();
  delete memstream;
  return true;
}

以上為一個使用管道獲取命令列的的執行結果的。

使用程式碼

TStringList *StrList=new TStringList;
AnsiString strcmd;

RunCmd(strcmd,StrList);

結果保留再StrList中。

 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-997997/,如需轉載,請註明出處,否則將追究法律責任。

相關文章