gpt4 book ai didi

c++ - 64 位 cygwin 下的 fstream 问题

转载 作者:行者123 更新时间:2023-11-30 04:29:03 25 4
gpt4 key购买 nike

实际上我不喜欢在 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;
}

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

预期的结果是:

4
8
160008

所有操作均在 Cygwin 下执行。用g++.exe编译代码,结果是对的。

但是当我使用 x86_64-w64-mingw32-g++.exe(只有它可以生成 64 位二进制文​​件)时,结果是有线的。

4
8
160506

它是有线的,额外的字节有什么用?我在这里试试运气。

感谢您的任何建议。

最佳答案

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

尝试像这样打开输出流:

ofstream fs(file, ios_base::binary);

关于c++ - 64 位 cygwin 下的 fstream 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9695874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com