mat*_*w3r 2 c++ file-io file-format
我已经实现了菱形算法,我想以文件格式存储地图数据.我主要是C++的初学者,或者至少在文件读写方面,所以我在哪里存储大量数据存在问题.
例如,如果我创建一个65*65的地图,那么它是16384个三角形,每个都有3个坐标,3个法线坐标.当然我可以把它分成例如4 32*32地图片,但它仍然很多.当然真正重要的是速度,在txt中写入所有数据没有问题,但它确实很慢,特别是当我增加地图大小时.
我不是真的需要一个来源,而是需要阅读或从中学习的东西.
您可以尝试将坐标写为原始二进制数据.退房ostream::write
并且istream::read
.另外,您也可以使用阅读C-路/写文件(fopen
,fread
,fwrite
,fclose
),这将避免很多铸造的.您必须以二进制模式打开文件才能使用.
如果您的文件需要可移植到其他平台,则必须考虑字节顺序,结构填充,整数大小等.
例:
#include <cassert>
#include <fstream>
struct Point {float x; float y; float z;};
bool operator==(const Point& p1, const Point& p2)
{
return (p1.x == p2.x) && (p1.y == p2.y) && (p1.z == p2.z);
}
int main()
{
Point p1 = {1, 2, 3};
Point p2 = {4, 5, 6};
std::ofstream out("data.dat", std::ios::binary);
// Write Point as a binary blob of bytes
// Lazy, but less portable way (there could be extra padding)
out.write(reinterpret_cast<const char*>(&p1), sizeof(p1));
// More portable way
out.write(reinterpret_cast<const char*>(&p2.x), sizeof(p2.x));
out.write(reinterpret_cast<const char*>(&p2.y), sizeof(p2.y));
out.write(reinterpret_cast<const char*>(&p2.z), sizeof(p2.z));
out.close();
Point p3;
Point p4;
std::ifstream in("data.dat", std::ios::binary);
// Read Point as a binary blob of bytes
// Lazy, but less portable way (there could be extra padding)
in.read(reinterpret_cast<char*>(&p3), sizeof(p3));
// More portable way
in.read(reinterpret_cast<char*>(&p4.x), sizeof(p4.x));
in.read(reinterpret_cast<char*>(&p4.y), sizeof(p4.y));
in.read(reinterpret_cast<char*>(&p4.z), sizeof(p4.z));
assert(p1 == p3);
assert(p2 == p4);
}
Run Code Online (Sandbox Code Playgroud)
您可能还对Boost.Serialization库感兴趣.它支持二进制存档,这可能比文本存档快得多.它还知道如何序列化标准库容器.