gpt4 book ai didi

c++ - 不使用 reinterpret_cast 读取二进制数据

转载 作者:可可西里 更新时间:2023-11-01 17:55:26 24 4
gpt4 key购买 nike

只是因为在我编写读取二进制 STL 文件的程序之前,我从未读取过二进制文件。我使用带有 char* 参数的 ifstream 读取成员。为了将我的结构转换为 char*,我使用了 reinterpret_cast。但据我所知,我读过的每本关于 C++ 的书都说过类似“除非你必须使用,否则不要使用 reinterpret_cast”之类的话。有什么更好的方法来读取二进制数据,不一定是直接读取,但最终读取到一个结构中并且不需要 reinterpret_cast?

主要功能:

std::ifstream in (cmdline[1].c_str(), std::ios::binary);

in.seekg(80, std::ifstream::beg); //skip header

int numTriangle;
in.read (reinterpret_cast<char*>(&numTriangle), sizeof(int)); //determine number of triangles
//create triangle data type and read data
triangle* t = new triangle();
for (int i = 0; i < numTriangle; ++i) {
in.read(reinterpret_cast<char*>(t), triangle::size);
std::cout << *t; // there's an opertor<< for triangle
}
delete t;

in.close(); //close file read from

三角形结构

//attempt to get the right size of a class without structure padding
#pragma pack(push)
#pragma pack(1)

//standard STL triangle data structure
struct triangle {
public:
float n[3]; //normals, 4*3=12 bytes

float x[3]; //first point of the triangle, 4*3=12 bytes
float y[3]; //second point of the triangle, 4*3=12 bytes
float z[3]; //third point of the triangle, 4*3=12 bytes

long int a; //attributes, 2 bytes

static const int size = 12+12+12+12+2; //sum of member variables
//static const int size = sizeof(n) + sizeof(x) + sizeof(y) + sizeof(z) + sizeof(a);
};
#pragma pack(pop)

(额外问题:#pragma pack(1) 不适用于 cygwins g++-4。我如何确定结构的大小?)

最佳答案

嗯,代码看起来不错。您甚至关心填充问题。我不明白你怎么能避免在这里转换。您可以执行以下顺序:

static_cast<char*>(static_cast<void*>(t))

但实际上,我并没有在我的代码中这样做。这只是对 char* 进行直接 reinterpret_cast 的一种更嘈杂的方式。 (参见 casting via void* instead of using reinterpret_cast)。


可以使用 sizeof 确定结构大小。您只需从 .cpp 中的类中初始化 static 成员(但是,编译器不知道 ::size< 的值 并且不能内联它)。
或者,您可以将其编写为静态内联成员函数。在它的主体中,类类型被认为是完整的,并且 sizeof (triangle) 是允许的。或者您可以像在评论中那样使用 sizeof,但使用类型而不是成员(指的是非静态成员,这种方式只在 C++0x 中允许):

//standard STL triangle data structure
struct triangle {
public:
float n[3]; //normals, 4*3=12 bytes

float x[3]; //first point of the triangle, 4*3=12 bytes
float y[3]; //second point of the triangle, 4*3=12 bytes
float z[3]; //third point of the triangle, 4*3=12 bytes

long int a; //attributes, 2 bytes

static int size() { return sizeof(triangle); } // this way
static const int size = sizeof(float[3])*4 + sizeof(long int); // or this way
};

但是,第二种方式并不好,因为您很容易在添加成员时忘记更新它。

关于c++ - 不使用 reinterpret_cast 读取二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2356636/

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