C++ read() 问题
我在 Visual Studio 2010 中的 C++ 中将大文件读入自己的缓冲区时遇到问题。下面是我的代码片段,其中 length 是我正在读入的文件的大小,在运行之前 bytesRead 设置为 0 ,文件是一个 std::ifstream。
buffer = new char[length];
while( bytesRead < length ){
file.read( buffer + bytesRead, length - bytesRead );
bytesRead += file.gcount();
}
file.close();
我注意到 gcount() 在第二次读取及以后返回 0,这意味着 read() 没有给我任何新字符,所以这是一个无限循环。我想继续阅读该文件的其余部分。我知道即使文件中有更多数据,eofbit 也会在第一次读取后设置。
我不知道我能做些什么来阅读更多内容。请帮忙。
I'm having trouble reading a large file into my own buffer in C++ in Visual Studio 2010. Below is a snippet of my code where length is the size of the file I'm reading in, bytesRead is set to 0 before this is run, and file is a std::ifstream.
buffer = new char[length];
while( bytesRead < length ){
file.read( buffer + bytesRead, length - bytesRead );
bytesRead += file.gcount();
}
file.close();
I noticed that gcount() returns 0 at the second read and onwards, meaning that read() did not give me any new characters so this is an infinite loop. I would like to continue to read the rest of the file. I know that the eofbit is set after the first read even though there is more data in the file.
I do not know what I can do to read more. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
确保以二进制模式 (
std::ios::binary
) 打开文件,以避免任何换行转换。使用文本模式可能会使您关于文件长度是可以从文件中读取的字节数的假设无效。无论如何,最好在读取后检查流的状态,如果出现错误则停止(而不是无限期地继续)。
Make sure you open your file in binary mode (
std::ios::binary
) to avoid any newline conversions. Using text mode could invalidate your assumption that the length of the file is the number of bytes that you can read from the file.In any case, it is good practice to examine the state of the stream after the read and stop if there has been an error (rather can continue indefinitely).
听起来您的流处于失败状态,此时大多数操作将立即失败。您需要
清除
流才能继续阅读。It sounds like your stream is in a failed state, at which point most operations will just immediately fail. You'll need to
clear
the stream to continue reading.