【问题标题】:How may I use the ifstream to read an info from a FIFO?如何使用 ifstream 从 FIFO 中读取信息?
【发布时间】:2017-03-28 15:11:06
【问题描述】:

我需要在一个循环中从 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 而不是>> 运算符——结果相同。

【问题讨论】:

  • 你能编辑你的问题吗?我不太清楚。
  • @Mohammad Tayyab,我该如何加强我的问题?
  • 你想做什么?只需阅读整个文件,然后?
  • 一行一行地读取一条信息,当它附加到另一侧的 FIFO 中时。
  • @SergeRoussak - 你怎么知道对方完成了追加信息?

标签: c++ linux fstream fifo


【解决方案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
    }
}

【讨论】:

    【解决方案2】:

    试试这个

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多