[英]C++ ifstream::read() - corrupts ifstream get pointer?
这里有人知道在read()调用后C ++ ifstream的get指针可能会损坏的方法吗? 我看到了一些真正奇怪的行为,我不知所措。 例如(说明性代码,而不是我实际运行的代码):
int main()
{
// datafile.bin is a 2MB binary file...
std::ifstream ifs( "datafile.bin", ios::binary );
ifs.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
int data[100];
std::istream::pos_type current_pos = ifs.tellg();
// current_pos = 0, as you'd expect...
ifs.read( reinterpret_cast<char*>(data), 100 * sizeof(int) );
// throws no exception, so no error bits set...
std::streamsize bytes_read = ifs.gcount();
// gives 400, as you'd expect...
current_pos = ifs.tellg();
// current_pos = 0x1e1a or something similarly daft
return 0;
}
我的示例显示了数组读取,但即使读取内置类型的单个值也是如此。 在读取正确之前,get指针会调用gcount()报告读取的正确字节数,但是之后,get指针完全是错误的。 并非每次read()调用都会发生这种情况-有时我会在一大堆东西之前弄清它们。 get指针可能是什么鬼东西? 我在做一些非常愚蠢的事情吗?
任何和所有帮助非常感谢...
西蒙
pos_type
不是整数类型,而是一个类,我不会尝试尝试解释其表示形式。 它可以隐式转换为整数类型,但是如果您在调试器中查看它,则会看到内部表示形式。
我尝试在Vista机器上的VS 2008中运行您的代码,但没有收到任何错误。 我对您的代码做了一些修改,以便在控制台上打印。
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// datafile.bin is a 2MB binary file...
std::ifstream ifs( "H_Line.bmp", ios::binary );
ifs.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit );
int data[100];
std::istream::pos_type current_pos = ifs.tellg();
cout<<current_pos<<endl; // current_pos = 0, as mentioned
ifs.read( reinterpret_cast<char*>(data), 100 * sizeof(int) );
// throws no exception, so no error bits set...
std::streamsize bytes_read = ifs.gcount();
cout<<bytes_read<<endl; // gives 400, as you have mentioned
current_pos = ifs.tellg();
cout<<current_pos<<endl; // FOR ME IT IS GIVING 400
return 0;
}
我已经在大小> 20 MB的BMP图像文件上对此进行了测试
您能否详细说明您使用的是哪台机器/编译器。 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.