同时写入和读取文件

Writing to and reading from a file at the same time

我有两个进程。一个写入文件,一个必须从中读取(同时..)。因此在给定时间文件有两个 fstream 打开(尽管它们可能在不同的进程中)。 我写了一个简单的测试函数来粗略地实现我需要的那种功能:

void test_file_access()
{
    try {
        std::string file_name = "/Users/xxxx/temp_test_folder/test_file.dat"; 

        std::ofstream out(file_name,
                          std::ios_base::out | std::ios_base::app | std::ios_base::binary);
        out.write("Hello\n", 7);

        std::this_thread::sleep_for(std::chrono::seconds(1));

        std::array<char, 4096> read_buf;
        std::ifstream in(file_name,
                         std::ios_base::in | std::ios_base::binary);

        if (in.fail()) {
            std::cout << "Error reading file" << std::endl;
            return;
        }

        in.exceptions(std::ifstream::failbit | std::ifstream::badbit);

        //Exception at the below line.
        in.read(read_buf.data(), read_buf.size());
        auto last_read_size = in.gcount();
        auto offset = in.tellg();

        std::cout << "Read [" << read_buf.data() << "] from file. read_size = " << last_read_size
                  << ", offset = " << offset << std::endl;

        out.write("World\n", 7);

        std::this_thread::sleep_for(std::chrono::seconds(1));

        //Do this so I can continue from the position I was before?
        //in.clear();

        in.read(read_buf.data(), read_buf.size());
        last_read_size = in.gcount();
        offset = in.tellg();

        std::cout << "Read [" << read_buf.data() << "] from file. read_size = " << last_read_size
                  << ", offset = " << offset << std::endl;

        //Remove if you don't have boost.
        boost::filesystem::remove(file_name);
    }
    catch(std::ios_base::failure const & ex)
    {
        std::cout << "Error : " << ex.what() << std::endl;
        std::cout << "System error : " << strerror(errno) << std::endl;
    }
}


int main()
{
    test_file_access();
}

运行,输出是这样的:

Error : ios_base::clear: unspecified iostream_category error
System error : Operation timed out

那么两个问题,

  1. 这里出了什么问题?为什么我会收到 Operation timed out 错误?
  2. 这是我需要完成的错误尝试吗?如果是这样,这里有什么问题?

您向该文件写入了 7 个字节,但随后尝试读取 4096 个字节。因此 in stream 将只读取 7 个字节并按要求抛出异常。请注意,如果您捕获此异常,则其余代码将正确执行,例如last_read_size 将为 7,您可以访问缓冲区中的这 7 个字节。