3

我只是使用了一些在 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
4

2 回答 2

3

readsome()是否可以进行非阻塞读取,因为这意味着实现定义(或由您的自定义 streambuf 成员定义showmanyc()),行为可能会有所不同。两者在我看来都是正确的。

于 2009-07-16T12:55:00.760 回答
0

断言“assert(buf1 == buf2);” 在调试模式下编译时失败,因为 buf1 和 buf2 只被告知要保留内存(即只是分配内存,而不是初始化它),并且运算符 == 实际上比较了两个具有未定义值的缓冲区。

至于“read(...)”和“readsome(...)”,我的建议是在大多数情况下坚持使用“read(...)”。

于 2009-09-21T20:54:33.593 回答