首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ ifstream::read() -是否损坏ifstream获取指针?

C++ ifstream::read() -是否损坏ifstream获取指针?
EN

Stack Overflow用户
提问于 2010-06-23 19:31:09
回答 2查看 2.2K关注 0票数 1

这里有没有人知道C++ ifstream的get指针在调用read()后可能会被破坏的方法?我看到了一些真正奇怪的行为,我不知道该怎么解释。例如(说明性代码,而不是我实际运行的代码):

代码语言:javascript
复制
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指针到底是怎么回事呢?我是不是做了什么非常愚蠢的事情?

任何帮助都非常感谢……

西蒙

EN

回答 2

Stack Overflow用户

发布于 2010-06-23 19:52:34

pos_type不是一个整型,而是一个类,我不会尝试解释它的表示。它可以隐式转换为整型,但如果您在调试器中查看它,您将看到内部表示。

票数 1
EN

Stack Overflow用户

发布于 2010-06-23 19:52:03

我试着在VS2008中运行你的代码在Vista机器上,但没有得到任何错误。为了在控制台上打印,我对您的代码进行了一些修改。

代码语言:javascript
复制
#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;
}

我已经在一个大小大于20MB的BMP图像文件上进行了测试

您能详细说明您使用的是哪种机器/编译器吗?谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3101164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档