0

I am writting a code which read a binary file with c++. At first, the code was tested in gcc 7.3 in Linux and it works. Now, I am testing the code with Visual Studio 2015 in Windows 7. after reading the 9th record from the file, eof() value becomes true and it breaks the loop while still hundreads of record remains.

I am not sure why the code behavior is different.

#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
    std::ifstream ifs;
    ifs.open("test.bin");

    while(!ifs.eof())
    {
        unsigned date;
        char time;
        float lat;
        float lon;
        float hs;
        float tp;
        float dp;
        float vw;
        float dw;

        ifs.read(reinterpret_cast<char*>(&date), sizeof(unsigned));
        ifs.read(reinterpret_cast<char*>(&time), sizeof(char));
        ifs.read(reinterpret_cast<char*>(&lat), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&lon), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&hs), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&tp), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&dp), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&vw), sizeof(float));
        ifs.read(reinterpret_cast<char*>(&dw), sizeof(float));
    }

    ifs.close();

    std::cout << "end of file" << std::endl;

    return 0;
}
Seong
  • 556
  • 4
  • 18
  • The only way it will exit the loop is if `ifs.eof()` is true. Other than that there is nothing apparent from what you posted that would explain any difference in behavior. You should add `if (!ifs.is_open()) return 1;` before you go into the loop. (especially since you hardcode a filename) – David C. Rankin May 11 '18 at 02:27
  • 6
    `ifs.open("test.bin");` -- That does not open a file as binary. You are opening the file in text mode, and more than likely you're being tripped up by the EOF marker for text files. Use `std::ios::binary` as the open flag. – PaulMcKenzie May 11 '18 at 02:38
  • https://stackoverflow.com/questions/13582804/why-can-windows-not-read-beyond-the-0x1a-eof-character-but-unix-can – andypea May 11 '18 at 02:45
  • @PaulMcKenzie Yes, you are right, I missed std::ios::binary. Thanks a lot. – Seong May 11 '18 at 03:39

0 Answers0