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

2024-01-18

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

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

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

程序在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()),行为可能会有所不同。两者对我来说似乎都是正确的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MSVC++7.1 中的 ifstream.read() 与 ifstream.readsome() 的相关文章

随机推荐