I don’t like working under Cygwin actually.
The problem is when I use 64-bits g++ to compile the same piece of code, I get unexpected different result.
The source code looks like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int rows = 200;
int cols = 200;
float data[rows*cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
data[i*cols+j] = i*cols+j;
}
}
const char *file = "tmp.txt";
ofstream fs(file);
if (fs.is_open())
{
fs.write((char*)&rows, sizeof(int));
cout << fs.tellp() << endl;
fs.write((char*)&cols, sizeof(int));
cout << fs.tellp() << endl;
fs.write((char*)data, sizeof(float)*rows*cols);
cout << fs.tellp() << endl;
fs.close();
}
return 0;
}
I am writing two integers and a block of float values into a binary file.
It prints out how many bytes it wrote.
The expected result is:
4
8
160008
All the actions were performed under Cygwin.
When the code was compiled with g++.exe, the result is right.
But when I use x86_64-w64-mingw32-g++.exe (only by which can generate 64-bits binary), the result is wired.
4
8
160506
It is wired, what extra bytes for?
I am trying my luck here.
Thank you for any advice.
My guess is that because the file is not opened in binary mode, every newline character (i.e., 0x0A byte) is being converted to a carriage-return+newline sequence. And I bet there just happen to be 500 such bytes in your array of floats.
Try opening your output stream like this: