您可以嘗試將原始二進制數據寫入您的座標。檢查出ostream::write
和istream::read
。或者,您可以使用讀取/寫入文件的C路(與fopen
,fread
,fwrite
,fclose
),這將避免大量的鑄造。你必須以二進制模式打開你的文件才能工作。
如果你的文件需要移植到其他平臺,你必須考慮的事情像endianness,struct padding,整數大小等
例子:
#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);
}
您可能也對Boost.Serialization庫感興趣。它支持binary archives,這可能比文本檔案快得多。它也知道如何序列化標準庫容器。
該文件是否需要可移植到其他平臺? – 2012-03-09 18:14:45
不,現在如果它與Windows兼容,對我來說很好。我還在學習,所以這並不重要。 – matthew3r 2012-03-09 18:17:13
您可能希望有一個谷歌周圍的'三角剝離'。 – 2012-03-09 18:20:33