Article View: gnu.g++.help
Article #158Re: stream class with popen?
From: Joe Buck
Date: Mon, 31 Aug 1992 19:04
Date: Mon, 31 Aug 1992 19:04
57 lines
2036 bytes
2036 bytes
In article <92Aug31.092656edt.133099@wotan.ai.toronto.edu> kramer@cs.toronto.edu ("Bryan M. Kramer") writes:
>Is there a stream class (g++ 2.2.2) that supports something
>like popen? I'd like to connect a stream to a pipe.
Yes, almost; that is, there is a class derived from streambuf called
procbuf that does what you want. Here is an example program. It takes
two arguments; the first is the name of a file, the second is a command.
The program reads the file and pipes it through the command. The command
is expanded by /bin/sh, so shell metacharacters work (or must be escaped
if that's not what you want).
Here's the program:
--------------------------------------------------------------------------
#include <procbuf.h>
#include <fstream.h>
#include <iostream.h>
main (int argc, char** argv) {
if (argc != 3) {
cerr << "Usage: " << argv[0] << " file 'command'\n";
return 1;
}
// open the file with an ifstream
ifstream istr(argv[1]);
if (!istr) {
cerr << argv[0] << ": Can't open file " << argv[1] << "\n";
return 1;
}
// create a procbuf with the command and attach it to an ostream.
// we could also have used ios::in and attached to an istream to
// read from a command.
procbuf pbuf(argv[2], ios::out);
ostream ostr(&pbuf);
// not sure this is the right way to check for failure
if (!ostr) {
cerr << argv[0] << ": Can't open pipe to '" << argv[2] << "'\n";
return 1;
}
// copy everything from one stream to the other
char ch;
while (istr.get(ch)) ostr.put(ch);
return 0;
}
--
Joe Buck jbuck@ohm.berkeley.edu
Technical Details
Message-ID:
<17tqf4INN8rm@agate.berkeley.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!sun-barr!ames!agate!forney.berkeley.edu!jbuckReferences:
<92Aug31.092656edt.133099@wotan.ai.toronto.edu>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!cs.utexas.edu!sun-barr!ames!agate!forney.berkeley.edu!jbuck From: jbuck@forney.berkeley.edu (Joe Buck) Newsgroups: gnu.g++.help Subject: Re: stream class with popen? Date: 31 Aug 1992 19:04:04 GMT Organization: U. C. Berkeley Lines: 57 Message-ID: <17tqf4INN8rm@agate.berkeley.edu> References: <92Aug31.092656edt.133099@wotan.ai.toronto.edu> NNTP-Posting-Host: forney.berkeley.edu