2

I must be missing something simple here, but I am trying to write and read a binary file in C++.

    ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
    file3.write((char*)(&i), sizeof(int));
}

ifstream file4("C:\\data2.txt", ios::in | ios::binary);

int temp;
while (!file4.eof()) {
    file4.read((char*)(&temp), sizeof(int));
    cout << temp << endl;
}

The file looks like it is getting created properly when viewed with a hex editor. However, as I go to read the file it reads 1 random junk value and quits vs. listing out all the numbers.

Update

I made a slight update based on the comments and all seems good now. On Windows the close made a difference and I did fix the loop condition.

    ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
    file3.write((char*)(&i), sizeof(int));
}

file3.close();
ifstream file4("C:\\data2.txt", ios::in | ios::binary);

//cout << file4.eof();
int temp;
while (!file4.read((char*)(&temp), sizeof(int)).eof()) {
    cout << temp << endl;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
ControlAltDelete
  • 3,576
  • 5
  • 32
  • 50

1 Answers1

1

You might not have permission to write to c:\\file, so you should check if you can. As for using .eof() see this topic. Finally, you might want to close the file before you open it again for reading. Here is your example tweaked:

#include<iostream>
#include<fstream>

int main()
{
    std::ofstream file3("data2.txt", std::ios::binary);
    if (file3)
    {
        for (int i = 0; i < 100; i++)
        {
            file3.write((char*)(&i), sizeof(int));
        }
        file3.close();
    }

    std::ifstream file4("data2.txt", std::ios::binary);

    int temp;
    while (file4)
    {
        file4.read((char*)(&temp), sizeof(int));
        std::cout << temp << std::endl;
    }
}

Demo: http://coliru.stacked-crooked.com/view?id=8f519fcd05879855

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
  • Yep the close made a difference. I am coming from C and will while(file4) work. Does the file descriptor become 0 once eof is hit in c++? – ControlAltDelete May 29 '18 at 16:05
  • 1
    @ArnabC. I think [this link](http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool) should answer your question why file4 becomes false at the end of read – Killzone Kid May 29 '18 at 16:08