I'm trying to write and then read a file in a simple format: 3 lines for an ull
(unsigned long long) and two float[].
I'm not sure why but I can't get the expected values.
vector<float> flowX{};
vector<float> flowY{};
void Save(string filename)
{
ofstream fileTarget(filename);
fileTarget << flowX.size() << endl;
for (const auto& e : flowX) fileTarget << e;
fileTarget << endl;
for (const auto& e : flowY) fileTarget << e;
fileTarget << endl;
fileTarget.close();
}
size_t Read(string filename)
{
ifstream fileTarget(filename);
size_t size{};
string firstLine;
string xLine;
string yLine;
if (fileTarget.good())
{
getline(fileTarget, firstLine);
size = stoll(firstLine);
getline(fileTarget, xLine);
getline(fileTarget, yLine);
}
fileTarget.close();
auto* xArray = (float*)&xLine[0];
auto* yArray = (float*)yLine.c_str(); //same as above
vector<float> vX(xArray, xArray + size);
vector<float> vY(yArray, yArray + size);
flowX = vX;
flowY = vY;
return size;
}
I read (twice)
1.65012e-07 1.04306e-08 0.000175648 4.05171e-11 4.14959e-08 0.000175648 1.04297e-08 1.03158e-08
instead of the expected
3.141f, 2324.89f, 122.89f, 233.89f, 7.3289f, 128.829f, 29.8989f, 11781.8789f
In Read()
, since string
stores data in a contiguous memory, the reinterpretation to a float[] should be fine, shouldn't it ? (https://stackoverflow.com/a/1986974/1447389)
The endianness should not have changed.
I'm using VS2019 toolset 1.42 x64 with c++17.
Where am I doing wrong ?
EDIT
Checking if I'm writing in binary (with and without ios::binary
I get the same file) with hexdump:
$ hd RawSave.sflow
00000000 38 0d 0a 35 34 2e 38 39 32 2e 38 39 36 2e 38 39 |8..54.892.896.89|
00000010 37 2e 38 39 31 38 2e 38 39 32 39 2e 38 39 31 31 |7.8918.8929.8911|
00000020 31 2e 38 39 0d 0a 35 34 2e 38 39 32 2e 38 39 36 |1.89..54.892.896|
00000030 2e 38 39 37 2e 38 39 31 38 2e 38 39 32 39 2e 38 |.897.8918.8929.8|
00000040 39 31 31 31 2e 38 39 |9111.89|
00000047