我試圖讀取一個文件1kB,並使用boost.asio將每個數據寫入套接字。問題是,當我需要從文本文件中讀取最後一段數據並將其放入緩衝區時,它似乎不起作用。eof錯誤讀取文本文件的片段並寫入boost.asio套接字
我需要一種方法來打印緩衝區的最後部分而不打印整個緩衝區(因爲它包含了從環的上一次迭代剩菜)
int portNumber = 2002;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), portNumber));
tcp::socket socket(io_service);
acceptor.accept(socket);
boost::system::error_code ignored_error;
int length;
char* buffer = new char[1025];//1024 bytes for data, 1 byte for seqNum
//get file stream and open local file.
ifstream stream;
stream.open("SampleFile.txt", ios::binary);
stream.seekg(0, ios::end);
length = stream.tellg();
stream.seekg(0, ios::beg);
while (!stream.eof())
{
//char sequenceNumber = '0';
stream.read(buffer, 1024);
buffer[1024] = sequenceNumber;//set last pos to seq num
boost::asio::write(socket, boost::asio::buffer(buffer),
boost::asio::transfer_all(), ignored_error);
.
. //do other things
.
}
這將最終什麼都寫在插座(假設客戶端正在協作),除了該文件的一部分末尾將被寫入兩次。
見http://stackoverflow.com/questions/6740425/cant-write-the-last-part-of-a-txt-file-to-cout-using- ifstream/6740686 –