I have question similar to this boost:asio file read.
does boot::asio support reading regular file from file system in async read function ?
I tried below code but it does not seem to work.
#include <iostream>
#include <fstream>
#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
void handleRead(const boost::system::error_code& error, std::size_t bytesRead) {
if (!error) {
// Process the read data here
std::cout << "Read " << bytesRead << " bytes" << std::endl;
} else {
std::cerr << "Error: " << error.message() << std::endl;
}
}
int main() {
boost::asio::io_context ioContext;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> workGuard(ioContext.get_executor());
const char* filename = "example.txt";
// Open the file
int fileDescriptor = open(filename, O_RDONLY);
if (fileDescriptor == -1) {
std::cerr << "Failed to open file: " << filename << std::endl;
return 1;
}
// Wrap the file descriptor with a stream_descriptor
boost::asio::posix::stream_descriptor file(ioContext, fileDescriptor);
// Create a buffer to hold the file data
const std::size_t bufferSize = 1024;
std::vector<char> buffer(bufferSize);
// Read the file asynchronously
boost::asio::async_read(file, boost::asio::buffer(buffer),
boost::asio::transfer_at_least(1),
boost::bind(&handleRead, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
// Run the I/O service
ioContext.run();
return 0;
}
I can see my handleRead being called but the bytesRead coming as 1024 always irrespective of file size. The file has only few bytes of data.