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