Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifstream.eof() - end of file is reached before the real end

I have a roughly 11.1G binary file where stores a series of the depth frames from the Kinect. There are 19437 frames in this file. To read one frame per time, I use ifstream in fstream but it reaches eof before the real end of the file. (I only got the first 20 frames, and the function stops because of the eof flag)

However, all frames can be read by using fread in stdio instead.

Can anyone explain this situation? Thank you for precious time on my question.

Here are my two functions:

// 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;
}

Again, thank you for precious time on my question

like image 287
willSapgreen Avatar asked Feb 22 '13 22:02

willSapgreen


1 Answers

You need to open the stream in binary mode, otherwise it will stop at the first byte it sees with a value of 26.

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

As for why 26 is special, it's the code for Ctrl-Z which was a convention used to mark the end of a text file. The history behind this was recorded in Raymond Chen's blog.

like image 57
Mark Ransom Avatar answered Oct 01 '22 00:10

Mark Ransom