簡體   English   中英

使用popen作為“寫入文件”的替代,然后“使用ifstream從中讀取”c ++

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

我是初學者,所以如果問題顯而易見,請繼續。

當前版本的代碼如下所示。 output.txt使用ifstream打開,然后送到Coll類型的對象,因為它理解“理解”生成的output.txt文件的格式。

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

我的目標是擺脫中間的output.txt,並做如下所示。

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

這會產生以下錯誤:

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

你能建議任何補救措施嗎?

你的問題是popen只提供了一個FILE * ,我不相信有任何(便攜,可靠)的方法將它轉換成文件流。 所以你將不得不處理使用fgets讀取一行作為C字符串和stringstream將其轉換為您的類型,或使用fscanf或類似。

可能這可以與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的類型為FILE ,沒有>>運算符。 你需要使用像fread()fwrite() 你也沒有獲得ifstream借給你的所有奇特類型的轉換,如果你要使用FILE你基本上必須直接讀取和寫入位。

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

這是從當前文件位置讀取內存並將其放入變量inputout ,其大小為Coll x 1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM