如何在C++中同时写入和读取文件

How to write to and read from a file simultaneously in C++

本文关键字:读取 文件 C++      更新时间:2023-10-16

我需要写两个程序write.cpp&CCD_ 2同时运行。其中一个写入(覆盖)文件,另一个从中读取

基本上,文件中总是只有一行。

write.cpp成功执行操作,但read.cpp没有显示任何内容。使用tail -f也显示错误的结果。

write.cpp:

#include <stdio.h>
#include <ctime>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
  ofstream myfile;
  int i = 70;
  char c;
  while(i <85)
  {
      myfile.open ("example.txt");
      c = i++;
      myfile << c << endl;
      myfile.close();
      sleep(1);
  }
  return 0;
}

read.cpp:

#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      sleep(1);
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

我可以知道这两个程序的哪一部分导致了问题吗?我该如何解决它?

您在编写器中做了正确的事情,但一旦读取到文件末尾,输入流将变得不可用,直到设置了fail条件。最好的解决方案可能是完全按照您在编写器中所做的操作:每次在读取循环中打开和关闭文件。

请注意,有时文件是空的;当您在编写器中打开要写入的文件时,它会被截断,如果读取器恰好在此时尝试读取,它会发现一个空文件。(这没什么大问题;只要注意,如果发现空行,可能会跳过sleep。)

为了在我对您之前的问题的回答中添加一些细节,如果您坚持使用ipc文件,下面是如何使用Boost的进程间通信来实现这一点。

一个作家可能是这样的:

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <fstream>
#include <iostream>
int main()
{
    using namespace boost::interprocess;
    std::string line, shared_filename = "shared";
    {
        std::ofstream create_shared_file(shared_filename.c_str());
    }
    for (;;)
    {
        std::cout << "Enter some text: ";
        std::cin >> line;
        try
        {
            file_lock lock(shared_filename.c_str());
            scoped_lock<file_lock> lock_the_file(lock);
            std::ofstream shared_file(shared_filename.c_str(), std::ofstream::trunc);
            shared_file << line << std::endl;
            shared_file.flush();
        }
        catch (interprocess_exception const& e)
        {
            std::cerr << e.what() << std::endl;
        }
    }
}

对应的阅读器:

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <fstream>
#include <iostream>
#include <unistd.h>
int main()
{
    using namespace boost::interprocess;
    std::string line, shared_filename = "shared";
    for (;;)
    {
        try
        {
            file_lock lock(shared_filename.c_str());
            std::cout << "Waiting for file lock..." << std::endl;
            sharable_lock<file_lock> lock_the_file(lock);
            std::cout << "Acquired file lock..." << std::endl;
            std::ifstream shared_file(shared_filename.c_str());
            shared_file >> line;
            if (line.empty())
            {
                std::cout << "Empty file" << line << std::endl;
            }
            else
            {
                std::cout << "Read: " << line << std::endl;
            }
        }
        catch (interprocess_exception const& e)
        {
            std::cerr << "Could not lock " << shared_filename << ": " << e.what() << std::endl;
        }
        std::cout << "Sleeping..." << std::endl;
        sleep(2);
    }
}