我如何使用ifstream从FIFO读取信息?

时间:2017-03-28 15:11:06

标签: c++ linux fstream fifo

我需要在一个循环中从FIFO读取信息(字符串),而另一个应用程序将写入它。我如何使用ifstream来做到这一点?

我尝试过这样一个简单的算法:

ifstream fifo("/path/to/file");

while(true)
{
  // Check, if we need to break the cycle etc...
  if(!fifo.eof())
  {
    string s;
    fifo >> s;
    // Do something...
  }
}

但它只读取第一行。我试图添加seekg(0)的调用,但这并没有得到任何结果。我尝试使用getline代替>>运算符 - 结果相同。

2 个答案:

答案 0 :(得分:1)

设置eof标志后,它会一直保持到您清除它为止。以下可能有效:

string s;
while (true) {
    fifo >> s;
    if (fifo.eof()) {
        sleep(1); // wait for another app to write something
        fifo.clear();
    }
    else {
        // do what you want with the string s
    }
}

答案 1 :(得分:0)

试试这个

ifstream fifo;
fifo.open("/path/to/file");

char output[100];

if (fifo.is_open()) {

   while (!fifo.eof()) {

      fifo >> output;
      //do whatever you want with the output

   }

}
else cout << "Cant open the file"<<endl;