2013-07-25 151 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 << ';';