简体   繁体   English

使用popen作为“写入文件”的替代,然后“使用ifstream从中读取”c ++

[英]Using popen as a substitue for “write to file” then “use ifstream to read from it” c++

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. output.txt使用ifstream打开,然后送到Coll类型的对象,因为它理解“理解”生成的output.txt文件的格式。

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. 我的目标是摆脱中间的output.txt,并做如下所示。

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? 你能建议任何补救措施吗?

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. 你的问题是popen只提供了一个FILE * ,我不相信有任何(便携,可靠)的方法将它转换成文件流。 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. 所以你将不得不处理使用fgets读取一行作为C字符串和stringstream将其转换为您的类型,或使用fscanf或类似。

May be this could work with pstream : 可能这可以与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  ">>"
}

f is of type FILE which does not have an >> operator. f的类型为FILE ,没有>>运算符。 You need to use things like fread() and fwrite() . 你需要使用像fread()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. 你也没有获得ifstream借给你的所有奇特类型的转换,如果你要使用FILE你基本上必须直接读取和写入位。

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. 这是从当前文件位置读取内存并将其放入变量inputout ,其大小为Coll x 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM