使用 fstreamtellg 读取流的一部分直到结束
我有这个简单的代码,需要获取正在写入的大型日志文件的一部分。在某些时候,它会存储从返回的当前位置 流位置开始 = istream::tellg(); 方法。 稍后,代码必须从流中读取缓冲区,从头到尾。代码大致如下:
streampos start = my_stream.tellg();
... // do some stuff with logging
streampos end = my_stream.tellg();
const streamsize size_to_read = (end - start);
char *buf = new char[size_to_read];
lock (m_logReadLock);
{
my_stream.flush();
my_stream.seekg(start);
my_stream.read(buf, size_to_read);
size_read = my_stream->gcount();
}
unlock (m_logReadLock);
我观察到的效果是 size_read 比 size_to_read 小,并且流设置了 eof 标志。结束指针不应该准确指定流结束的位置并且 read() 方法返回准确的数据量吗? 没关系,我可以通过检查 eof 标志来解决这个问题。 然而,谁能解释一下这种效应呢?
谢谢。
I have this simple code that needs to get a chunk of a large log file that is being written into. At some point it stores the current location returned from
streampos start = istream::tellg();
method.
Later on the code has to read from the stream a buffer from the start till the end. The code is approximately like this:
streampos start = my_stream.tellg();
... // do some stuff with logging
streampos end = my_stream.tellg();
const streamsize size_to_read = (end - start);
char *buf = new char[size_to_read];
lock (m_logReadLock);
{
my_stream.flush();
my_stream.seekg(start);
my_stream.read(buf, size_to_read);
size_read = my_stream->gcount();
}
unlock (m_logReadLock);
The effect that I'm observing is that size_read is smaller than size_to_read and the stream has its eof flag set. Shouldn't the end pointer specify exactly where the stream ends and read() method return that exact amount of data?
It is fine, I can work round it by checking the eof flag.
However, can anyone provide the explanation for this effect?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎是在
stream_loc
而不是my_stream
上调用gcount
。You seem to be calling
gcount
onstream_loc
instead ofmy_stream
.http://groups.google.com/group/comp .lang.c++/browse_thread/thread/709cde3942e64d6c#
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/709cde3942e64d6c#