c++ eof()-在真实的结束之前到达文件结束

jpfvwuh4  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(101)

我有一个大约11. 1 G的二进制文件,其中存储了一系列来自Kinect的深度帧。此文件中有19437帧。为了每次读取一帧,我在***fstream***中使用***ifstream***,但它在文件真实的结束之前到达***eof***。(我只得到了前20帧,函数因为***eof***标志而停止)
但是,可以通过在***stdio***中使用***fread***读取所有帧。
有人能解释一下这种情况吗?谢谢你花宝贵的时间回答我的问题。
下面是我的两个函数:

// ifstream.read() - Does Not Work: the loop will stop after 20th frame because of the eof flag
ifstream depthStream("fileName.dat");
if(depthStream.is_open())
{
  while(!depthStream.eof())
  {
    char* buffer = new char[640*480*2];
    depthStream.read(buffer, 640*480*2);

    // Store the buffer data in OpenCV Mat

    delete[] buffer;
  }
}

// fread() - Work: Get 19437 frames successfully
FILE* depthStream
depthStream = fopen("fileName.dat", "rb");
if(depthStream != NULL)
{
  while(!feof(depthStream))
  {
    char* buffer = new char[640*480*2];
    fread(buffer, 1, 640*480*2, depthStream);

    // Store the buffer data in OpenCV Mat

    delete[] buffer;
}

再次感谢您花宝贵时间回答我的问题

nx7onnlm

nx7onnlm1#

您需要以二进制模式打开流,否则它将在它看到的第一个字节处停止,值为26。

ifstream depthStream("fileName.dat", ios_base::in | ios_base::binary);

至于为什么26是特殊的,它是Ctrl-Z的代码,这是一个用来标记文本文件结束的约定。这背后的历史记录在Raymond Chen的博客文章Why do text files end in Ctrl+Z?中。

相关问题