Thread View: gnu.g++.help
2 messages
2 total messages
Started by "Bryan M. Kramer"
Mon, 31 Aug 1992 13:27
stream class with popen?
Author: "Bryan M. Kramer"
Date: Mon, 31 Aug 1992 13:27
Date: Mon, 31 Aug 1992 13:27
7 lines
652 bytes
652 bytes
Is there a stream class (g++ 2.2.2) that supports something like popen? I'd like to connect a stream to a pipe. |Bryan M. Kramer, Ph.D. 416-978-7330, fax 416-978-1455| |Department of Computer Science, University of Toronto | |6 King's College Road, Room 283E | |Toronto, Ontario, Canada M5S 1A4 |
Re: stream class with popen?
Author: 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
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads