0

Here is the code. I notice the first number 57.98 cannot shown correctly. After reading in hex I find out that 57.98 converted to 9 bytes when I write in to the file. How can I fix this?

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
int main()
{
    fstream f("Test.dat");

    // Defining a vector to write
    vector<double> data = { 57.98, 11.99, 11.00, 79.50, 99.99, 6.99, 21.50, 7.50 };

    for (size_t i = 0; i < data.size(); i++) {
        f.seekp(static_cast<int64_t>(i) * sizeof(double));
        f.write(reinterpret_cast<char*>(&data.at(i)), sizeof(double));
    }
    
    for (size_t i = 0; i < data.size(); i++) {
        double d;
        f.seekg(static_cast<int64_t>(i) * sizeof(double));
        f.read(reinterpret_cast<char*>(&d), sizeof(double));
        cout << d << ", ";
    }

    f.close();

    return 0;
}
Output: 
8.62172e+285, 11.99, 11, 79.5, 99.99, 6.99, 21.5, 7.5,
hlhc
  • 31
  • 4
  • How did you write the file in the first place? Did you open it as binary? – Devolus Feb 19 '21 at 10:16
  • I write it with f.write(), I use hex editor to open the file and it get the first double 57.98 write 9 bytes in total. 3D 0D 0A D7 A3 70 FD 4C 40 – hlhc Feb 19 '21 at 10:19
  • 2
    Yep, that's the issue. You are on Windows system and you opened file in text mode (the default). In this mode, byte `0x0A` (newline character) gets replaced with OS-specific line ending, `0x0D 0x0A` for Windows. Open your file in binary mode (`std::fstream f("Test.dat", std::ios::binary);`) and it should be fixed. – Yksisarvinen Feb 19 '21 at 10:21
  • That is a text file. But you are reading the file like it were binary. Or it is a binary (looking like a text file) but you opened it as text. – Devolus Feb 19 '21 at 10:22
  • If you wrote `fwrite(sizeof(double))` then it should be 8 bytes long, not 9, so there is something wrong with either your input or output files. – Devolus Feb 19 '21 at 10:23
  • I forgot to open it with binary, the issue is now fix. Thanks! – hlhc Feb 19 '21 at 10:26

0 Answers0