nakiya
nakiya

Reputation: 14413

Writing to and reading from a file at the same time

I have two processes. One writes to a file, one has to read from it (At the same time..). So there's two fstreams open at a given time for the file (Although they may be in different processes). I wrote a simple test function to crudely implement the sort of functionality I need:

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();
}

Run, and the output is like this:

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

So two questions,

  1. What is going wrong here? Why do I get an Operation timed out error?
  2. Is this an incorrect attempt to do what I need to get done? If so, what are the problems here?

Upvotes: 2

Views: 1731

Answers (1)

user7860670
user7860670

Reputation: 37549

You write into this file 7 bytes, but then try to read 4096 bytes. So in stream will read only 7 bytes and throw an exception as requested. Note that if you catch this exception the rest of the code will be executed correctly, e.g. last_read_size will be 7 and you can access those 7 bytes in buffer.

Upvotes: 1

Related Questions