eof 读取文本文件片段并写入 boost.asio 套接字时出错
我尝试一次读取 1kB 的文件,并使用 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
.
}
这最终会将所有内容写入套接字(假设客户端正在合作),除了一部分文件末尾的部分将被写入两次。
I'm trying to read a file 1kB at a time and write each piece of data to a socket using boost.asio. The problem is that when I need to read the last piece of data from the text file and put it in the buffer, it doesnt seem to work.
I need a way to print the last part of the buffer without printing the whole buffer (because it contains leftovers from the previous iteration of the loop)
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
.
}
This will eventually write everything to the socket (assuming the client end is cooperating) except that a portion of the end of the file will get written twice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1)您没有正确计算最终缓冲区的大小。
2) 您没有正确测试流的错误或 eof 条件。
试试这个:
1) You aren't correctly computing the size of the final buffer.
2) You aren't correctly testing the stream for error or eof conditions.
Try this: