2013-07-25 149 views
0

我用C++编写了一个在空间中移动的球(3D点)的代码。我有它的所有移动位置。我的意思是,它传递的所有路径点。如何写入和读取二进制文件的指向?

我不得不写它所有的位置\点成二进制文件,然后才能恢复运动\路径读它。例如,如果我把球向右移动,我会想要保存所有通过的位置,然后我可以读取它们,并画出球移动相同,恢复其路径。

我看到了二进制文件的一个例子,但它并没有说太多,对我说:

// reading a complete binary file 
#include <iostream> 
#include <fstream> 
using namespace std; 

ifstream::pos_type size; 
char * memblock; 

int main() { 
    ifstream file ("example.bin", ios::in|ios::binary|ios::ate); 
    if (file.is_open()) 
    { 
    size = file.tellg(); 
    memblock = new char [size]; 
    file.seekg (0, ios::beg); 
    file.read (memblock, size); 
    file.close(); 

    cout << "the complete file content is in memory"; 

    delete[] memblock; 
    } 
    else cout << "Unable to open file"; 
    return 0; 
} 

是否自动创建该文件?那么在哪?那么写点和读点(X,Y,Z)如何?我应该通过二进制字节写入吗?或作为点和文件使其二进制..?

+0

你为什么要读取和写入到二进制文件?为什么不是文本格式? – herolover

+0

你的例子只是读取一个文件到内存中,没有解释文件实际包含什么,也没有写入文件的例子。请谷歌搜索 - 有大量的例子有... – John3136

+0

herolover,我要实现它在一个被称为每一帧(更新功能),所以我并不需要一个大的文件,但小功能。 和John3136,我一直在谷歌上搜索(:? –

回答

1

你可以写一个点(X,Y,Z)为二进制文件由冒号分隔坐标e.g,并点用分号:

int X=10, Y=12, Z=13; 
ofstream outfile("points.bin", ios::binary); 
if (!outfile) 
    cerr << "Could not open a file" << endl; 
else 
    outfile << X << ',' 
      << Y << ',' 
      << Z << ';';