delphi中如何使用popen ?請幫忙
一直很羨慕C語言中的popen函數, 可以很方便的讀取管道.
在crtdll.dll中發現_popen函數,
然後在dev-cpp中查看引用方法 ,改成Delphi下也可使用.
問題是.
popen只能在console程序中使用,
gui程序中popen返為nil,或 gui程序用 -CC編譯.
請問該如何修改?
console, gui,編譯對 input,output的處理有何差異?
謝謝.
以下是crtdll.pas及 ptest.dpr代碼,
crtdll.pas
unit crtdll;
interface
const crtlib = 'crtdll.dll' ;
type _iobuf = record
_ptr : PChar;
_cnt : Integer;
_base: PChar;
_flag :Integer;
_file:Integer;
_charbuf :INteger;
_bufsiz :Integer;
_tmpfname :PChar ;
end ;
type
pFILE = ^_iobuf;
cFile = _iobuf ;
Type
size_t = LongInt ;
function popen ( _command : PChar; _mode : PChar ) : PFILE; stdcall external crtlib name '_popen';
function pclose ( Var _pf : cFile ) : Integer; stdcall external crtlib name '_pclose';
function fopen ( _filename : PChar;
_mode : PChar ) : pFile; external crtlib;
function fclose ( Var FStream : cFile ) : Integer;stdcall; external crtlib;
function feof ( Var FStream : cFile ) : Integer; stdcall external crtlib;
function fread ( Var _ptr;
_size : size_t;
_nelem : size_t;
Var FStream : cFile ) : SIZE_T; stdcall; external crtlib;
implementation
end.
測試:
program ptest;
{$APPTYPE CONSOLE}
uses
SysUtils,
windows,
crtdll in '..\public\crtdll.pas';
const
BSIZE=50 ;
var
fp :PFILE ;
cmd,m :String ;
cnt :Integer ;
buf :String;
begin
{ TODO -oUser -cConsole Main : Insert code here }
cmd :='type c:\boot.ini' ;
m :='r';
fp := popen(PChar(cmd),PChar(m)) ;
writeln(sizeof(_iobuf)) ;
while not (feof(fp^) <>0) do begin
setlength(buf,BSIZE) ;
FillChar(buf[1], BSIZE, #0);
cnt :=fread(buf[1] ,1,BSIZE,fp^) ;
write(buf) ;
end ;
fclose(fp^) ;
end.