gpt4 book ai didi

c++ - ifstream.read() 与 MSVC++7.1 中的 ifstream.readsome()

转载 作者:太空狗 更新时间:2023-10-29 21:31:07 29 4
gpt4 key购买 nike

我只是采用了一些在 Linux 下开发的文件阅读器的旧代码,并尝试在我的 Windows 项目中使用完全相同的代码,该项目是用 MSVC++7.1 编译的。代码编译没有任何问题,但根据 Windows 上的文件阅读器,文件似乎是空的。

我将问题追溯到 ifstream.readsome(),它没有从文件中读取任何内容,也没有在流上设置任何错误标志。下面提供的代码可以在 Linux 和 Windows 上编译,但 Linux 可以按预期工作。

代码打开一个文件并使用 read() 一次读取文件的前 512 个字节,一次使用 readsome()。两个结果都存储在两个 vector 中,在程序结束时进行比较。预期结果是两个 vector 相等。

程序在 Windows XP 上的结果输出贴在源代码下方。

如果有人有任何想法或猜测这段代码可能出了什么问题,我很乐意听取他们的意见。

完整的demo源码:

#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>

int main()
{
const size_t BUFFER_SIZE(512);

std::ifstream in("some.file", std::ios::in | std::ios::binary);
if(in.is_open())
{
std::vector<char> buf1(BUFFER_SIZE);
std::vector<char> buf2(BUFFER_SIZE);
assert(buf1 == buf2);

if(in.seekg(0, std::ios_base::beg).good())
{
//read BUFFER_SIZE bytes from the file using read()
if(in.read(&buf1[0], buf1.size()).eof())
{
std::cerr << "read() only read " << in.gcount() << " bytes." << std::endl;
}
else
{
std::cout << "read() could read all 512 bytes as expected." << std::endl;
}
if(!in.good())
{
std::cerr << "read() set an error flag in ifstream." << std::endl;
}
}
else
{
std::cerr << "Can not test read()." << std::endl;
}
if(in.seekg(0, std::ios_base::beg).good())
{
//read BUFFER_SIZE bytes from the file using readsome()
std::streamsize bytesRead = in.readsome(&buf2[0], buf2.size());
if(bytesRead != BUFFER_SIZE)
{
std::cerr << "readsome() only read " << bytesRead << " bytes." << std::endl;
}
else
{
std::cout << "readsome() could read all 512 bytes as expected." << std::endl;
}
if(!in.good())
{
std::cerr << "readsome() set an error flag in ifstream." << std::endl;
}
}
else
{
std::cerr << "Can not test readsome()." << std::endl;
}

//should read from the same file, so expect the same content
assert(buf1 == buf2);
}

return 0;
}

Windows XP 上的输出:

read() could read all 512 bytes as expected.
readsome() only read 0 bytes.
Assertion failed: buf1 == buf2, file [...], line 60

最佳答案

readsome() 用于进行非阻塞读取,因为这恰恰意味着实现定义(或由您的自定义 streambuf 成员 showmanyc() 定义)、行为可以变化。两者对我来说似乎都是正确的。

关于c++ - ifstream.read() 与 MSVC++7.1 中的 ifstream.readsome(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137351/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com