64位cygwin下的fstream问题

时间:2012-03-14 04:20:12

标签: c++ cygwin mingw32

我不喜欢在Cygwin下工作。

问题是当我使用64位g ++编译同一段代码时,我得到了意想不到的不同结果。

源代码如下所示:

#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;
}

我正在将两个整数和一个浮点值块写入二进制文件。 它打印出它写的字节数。

预期结果是:

4
8
160008

所有行动均在Cygwin下进行。 当用g ++ .exe编译代码时,结果是正确的。

但是当我使用x86_64-w64-mingw32-g ++。exe(只能通过它生成64位二进制)时,结果是有线的。

4
8
160506

有线,多少字节用于? 我在这里试试运气。

感谢您的任何建议。

1 个答案:

答案 0 :(得分:2)

我的猜测是因为文件没有以二进制模式打开,所以每个换行符(即0x0A字节)都被转换为回车+换行序列。我打赌你的浮动数组中恰好有500个这样的字节。

尝试打开输出流,如下所示:

ofstream fs(file, ios_base::binary);
相关问题