C++ read() 问题

发布于 2024-12-11 17:47:58 字数 494 浏览 0 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笙痞 2024-12-18 17:47:58

确保以二进制模式 (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).

墨落画卷 2024-12-18 17:47:58

听起来您的流处于失败状态,此时大多数操作将立即失败。您需要清除流才能继续阅读。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文