0

I am a beginner so please be undertanding if the question is about sth obvious.

The current version of code is shown below. The output.txt is opened using ifstream and then fed to object of type Coll which is used because it understands "understands" the format of output.txt file generated.

std::system("./Pogram > output.txt");
Coll inputout;
    ifstream ifsout("output.txt");
    ifsout >> inputout;

My objective is to get rid of the intermediate output.txt and do sth like shown below.

FILE * f = popen("./Program", "r");
Coll inputout;
f >> inputout;

This yields the following error though:

error: no match for ‘operator>>’ in ‘f >> inputout’

Can you suggest any remedy to that?

Gleb
  • 53
  • 1
  • 6
  • A bit unusual, but if you really wanted your example code to work then you *could* implement `operator>>(FILE*, const Coll&)`. – Steve Jessop Aug 07 '13 at 16:27

3 Answers3

1

Your problem is that popen only provides a FILE *, and I don't believe there is any (portable, reliable) way to convert that into a file-stream. So you will have to deal with using fgets to read a line as a C string and stringstream to convert it to your type, or using fscanf or similar.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • I think you're right, but http://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor might help depending how portable the questioner needs the code to be. – Steve Jessop Aug 07 '13 at 16:25
  • You can always create your own std::streambuf to read from FILE*... but that might be overkill – rabensky Aug 07 '13 at 18:43
  • Yeah, unless you REALLY need to do this a lot - in which case creating a 'pipe' stream would be a better choice, I feel. – Mats Petersson Aug 07 '13 at 18:45
  • Thanks for all replies. Suggested methods didn't work, so I did brute-force by creating and added a "delete the temporary file" command at the end of code: std::system("rm output.txt") – Gleb Aug 08 '13 at 07:45
1

May be this could work with pstream :

#include <pstream.h>
#include <string>
#include <iterator>

int main()
{
  redi::ipstream proc("./Program");
  typedef std::istreambuf_iterator<char> it;
  std::string output(it(proc.rdbuf()), it());

  Coll inputout; 
  output>>inputout; // You might have overloaded  ">>"
}
P0W
  • 46,614
  • 9
  • 72
  • 119
0

f is of type FILE which does not have an >> operator. You need to use things like fread() and fwrite(). You also don't get all the fancy type conversions that ifstream lends to you, if you are to use FILE you basically have to read and write directly in bits.

fread(&inputout, sizeof(Coll), 1, f);

This is reading memory from the current file location and putting it into the variable inputout that is the size of a Coll x 1.

Lochemage
  • 3,974
  • 11
  • 11
  • That only works if the data is binary, and the first example code shows it using `>>` which is not used in binary file reads. – Mats Petersson Aug 07 '13 at 16:12