www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Reading stdout of an external process using pipes under windows

I decided to put some code here that allowed me read (via a 
streamed pipe) the stdout from an external process. I didn't see 
something like this before and when searching I only found the 
new std.process in phobos development branch which doesn't have a 
Windows version.

If anyone feels like doing a unix version go ahead...


import std.file, std.stdio, std.string, std.conv;

alias extern (C) FILE* function(const(char)*, const(char)*) 
alias extern (C) int function(FILE*) _pclose;
alias extern (C) int function(FILE*) _fgetc;

_popen  popen;
_pclose pclose;
_fgetc  fgetc;

   import core.sys.windows.windows;

   static this(){
     auto hMsvcrt = GetModuleHandleA("msvcrt.dll");
     popen  = cast(_popen)  GetProcAddress(hMsvcrt, "_popen");
     pclose = cast(_pclose) GetProcAddress(hMsvcrt, "_pclose");
     fgetc  = cast(_fgetc)  GetProcAddress(hMsvcrt, "fgetc"); 
     write("Bound functions: ");
     writefln("popen=%s, pclose=%s, fgetc=%s\n",popen, pclose, 
   /* ??? Posix anyone ??? */

void main(string[] args){
   int  i;
   auto pPipe = popen(toStringz("dir"), toStringz("rt"));
   if(pPipe != null){
     while((i = fgetc(pPipe)) != -1){
     writefln("\nProcess return: %d", pclose(pPipe));
     writeln("Command failed");
Sep 13 2012