我有一个2884765579字节文件。这双具有这种功能,它返回数检查:seekg()神秘失败
size_t GetSize() {
const size_t current_position = mFile.tellg();
mFile.seekg(0, std::ios::end);
const size_t ret = mFile.tellg();
mFile.seekg(current_position);
return ret;
}
我然后执行:
mFile.seekg(pos, std::ios::beg);
// pos = 2883426827, which is < than the file size, 2884765579
此设置failbit。 errno
未更改。我可以采取哪些措施来解决此问题?
我绝对相信说:
- 的文件大小是真的2884765579
pos
真的2884765579- 的failbit未.seekg之前设置()
- 失败位在.seekg()后面设置,并且在 ,之间没有其他调用10
- 打开文件与二进制标志
编辑:万一有人运行到同样的问题..使用此代码,我写了许多头痛少(仅在Windows工作)为您:
class BinaryIFile
{
public:
BinaryIFile(const string& path) : mPath(path), mFileSize(0) {
mFile = open(path.c_str(), O_RDONLY | O_BINARY);
if (mFile == -1)
FATAL(format("Cannot open %s: %s") % path.c_str() % strerror(errno));
}
~BinaryIFile() {
if (mFile != -1)
close(mFile);
}
string GetPath() const { return mPath; }
int64 GetSize() {
if (mFileSize)
return mFileSize;
const int64 current_position = _telli64(mFile);
_lseeki64(mFile, 0, SEEK_END);
mFileSize = _telli64(mFile);
_lseeki64(mFile, current_position, SEEK_SET);
return mFileSize;
}
int64 Read64() { return _Read<int64>(); }
int32 Read32() { return _Read<int32>(); }
int16 Read16() { return _Read<int16>(); }
int8 Read8() { return _Read<int8>(); }
float ReadFloat() { return _Read<float>(); }
double ReadDouble() { return _Read<double>(); }
void Skip(int64 bytes) { _lseeki64(mFile, bytes, SEEK_CUR); }
void Seek(int64 pos) { _lseeki64(mFile, pos, SEEK_SET); }
int64 Tell() { return _telli64(mFile); }
template <class T>
T Read() { return _Read<T>(); }
void Read(char *to, size_t size) {
const int ret = read(mFile, (void *)to, size);
if ((int)size != ret)
FATAL(format("Read error: attempted to read %d bytes, read() returned %d, errno: %s [we are at offset %d, file size is %d]") % size % ret % strerror(errno) % Tell() % GetSize());
}
template <class T>
BinaryIFile& operator>>(T& val) { val = _Read<T>(); return *this; }
private:
const string mPath;
int mFile;
int64 mFileSize;
template <class T>
T _Read() { T ret; if (sizeof(ret) != read(mFile, (void *)&ret, sizeof(ret))) FATAL("Read error"); return ret; }
};
'pos'是什么类型? – jamesdlin 2010-03-07 03:05:22
现在真正的问题是:你如何在Windows上获得64位文件位置(除了切换到64位操作系统)。我无法帮到那里,对不起。 – Tronic 2010-03-07 03:10:06
是的,那是你的问题。带有一个参数的'seekg'需要一个'streampos'参数,'seekg'有两个'streamoff'参数。后者必须签名。 – jamesdlin 2010-03-07 03:13:09