C++ boost asio Windows file handle async_read_until infinite loop - no eof

后端 未结 3 626
轮回少年
轮回少年 2021-02-07 23:00

I\'m using boost 1.50 with VS2010, reading using a Windows file HANDLE (which seems to be relatively uncommon compared to asio use with sockets).

Probl

3条回答
  •  囚心锁ツ
    2021-02-07 23:50

    A stream_handle will always read at offset zero. I think it's meant for sockets handles and useless for regular files.

    Calling async_read_until() gets 512 bytes if the streambuf doesn't already contain a newline. The first call reads a bit more than 7 lines. When seven lines are extracted the remainig characters ("LINE 8 abcdefghijklmno") don't have a newline and (the same) 512 bytes are appended.

    To solve the problem I'd suggest to use a random_access_handle. You have to track the file position manually and replace async_read_until with async_read_at.

    class AsyncReader
    {
      ...
      void start_read()
      {
        async_read_at(input_handle, input_offset, input_buffer, ...);
      }
    private:
      boost::asio::windows::random_access_handle input_handle;
      boost::uint64_t input_offset;
    };
    
    void AsyncReader::handle_read(const boost::system::error_code& error,
                                  std::size_t length)
    {
      input_offset += length;
      if (!error || error == boost::asio::error::eof)
      {
        ...
    

提交回复
热议问题