Question

I am trying to read in a binary file and write in chunks to multiple output files. Say if there are 25 4byte numbers in total and chunk size is set to 20, the program will generate two output files one with 20 integers the other with 5. However if I have a input file with 40 integers, my program generates three files, first 2 files both have 20 numbers, however the third file has one number which is the last one from the input file and it is already included in the second output file. How do I force the read position to move forward every time reading a number?

  ifstream fin("in.txt", ios::in | ios::binary);
  if(fin.is_open())
    {
      while(!fin.eof()){
        //set file name for each output file                                                                  
        fname[0] = 0;
        strcpy(fname, "binary_chunk");
        index[0] = 0;
        sprintf(index, "%d", fcount);
        strcat(fname, index);

        // open output file to write                                                                          
        fout.open(fname);

        for(i = 0; i < chunk; i++)
          {
            fin.read((char *)(&num), INT_SIZE);
            fout << num << "\n";

            if(fin.eof())
              {
                fout.close();
                fin.close();
                return;
              }
          }
        fcount ++;
        fout.close();
      }
      fout.close();
    }
Was it helpful?

Solution

The problem is most likely your use of while (!fin.eof()). The eofbit flag is not set until after you have tried to read from beyond the end of the file. This means that the loop will loop one extra time without you noticing.

Instead you should remember that all input operations returns the stream object, and that stream objects can be used as boolean conditions. That means you can do like this:

while (fin.read(...))

This is safe from the problems with looping while !fin.eof().

And to answer your question in the title: Yes, the file position is moved when you successfully read anything. If you read X bytes, the read-position will be moved forward X bytes as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top