gpt4 book ai didi

c++ - 在 C++ 中读取 .raw 文件

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

总的来说,我是 C++ 的新手,因此也是 C++ 的文件处理方面的新手。

我需要读取一个 .raw 文件,该文件具有 16 位整数,并且尺寸为 512 x 512

为此,我使用以下代码:

ifstream myData("myData.raw");
short value;
int i = 0;
char buf[sizeof(short)];
while (myData.read(buf,sizeof(buf)))
{
memcpy(&value, buf, sizeof(value));
cout << value << " ";
i++;
}

cout << endl << "Total count: " << i << endl;

我为 i 获得的值不是 512 x 512。所以我猜有些地方不对。

有人可以在这方面帮助我吗?

最佳答案

默认打开模式是“文本”,一些字符可能会被丢弃或被视为文件结尾。 ios::binary 停止了这些改变。

#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream myData("myData.raw", ios::binary);
short value;
int i = 0;
char buf[sizeof(short)];
while (myData.read(buf, sizeof(buf)))
{
memcpy(&value, buf, sizeof(value));
cout << value << " ";
i++;
}

cout << endl << "Total count: " << i << endl;
}

关于c++ - 在 C++ 中读取 .raw 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781876/

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