1

I opened a pipe to a program that reads text input.

This is what I am currently doing

FILE* p = popen("myprogram", "w");
string myBuff;
//write something to myBuff
fprintf(p, "%s\n", myBuff.c_str());

This is what I want to do

 p = popen("myprogram", "w");
 p << "my text" << endl;

Does Boost have something for this? I would assume this is a frequently encountered problem, how is it usually solved?

Mikhail
  • 7,749
  • 11
  • 62
  • 136
  • 1
    What is `File`? I think GCC ships with a stream-type object that wraps a C `FILE*`, which may be useful, but it's not part of the standard library. – Kerrek SB Mar 20 '12 at 20:32
  • 1
    possible duplicate of [Construct ofstream from stdio file](http://stackoverflow.com/questions/8073846/construct-ofstream-from-stdio-file) – Ben Jackson Mar 20 '12 at 20:32
  • It is not immediately obvious as to why this is a duplicate. The solution to my problem could be pipe specific; for example I am looking into using Boost.Process – Mikhail Mar 20 '12 at 20:43

2 Answers2

4

A quick and dirty solution that won't involve Boost would be to simply overload operator<< for your FILE* type.

FILE* operator<<(FILE* fptr, const std::string& input_string)
{
    fprintf(fptr, "%s\n", input_string.c_str());
    return fptr;
}

This won't work with the stream modifiers like std::endl, etc., but as noted, it gets the job done in a quick-and-dirty way. There's nothing wrong with Boost per-se, but I think for just trying to gain the ability to use operator<< syntax, it's a bit heavy.

Jason
  • 31,834
  • 7
  • 59
  • 78
  • Is there some massive performance hit when doing this? Or is this performance hit the same as one would find using streams? – Mikhail Mar 20 '12 at 20:38
  • 1
    Why would there be a massive performance hit? Both C++ streams and the libc functions for I/O have to go through the same kernel calls, so the performance of both interfaces should be very similar in the end. – Jason Mar 20 '12 at 20:39
0

boost has the Interprocess library which facilitates communication between processes. They also have in their sandbox, as an unofficial library, the Process library that facilitates inter-process communication using the standard pipes.

Nick Strupat
  • 4,928
  • 4
  • 44
  • 56