简体   繁体   中英

how to write and read points to binary file?

I've programmed a code in C++ of a ball that moves in the space (3D points). I have all its movements positions. I mean, all the path points it passed.

I have to write its all positions\\points into a binary file and then read it in order to restore the movements\\path. for example, if I move the ball up and right, I'll want to save all the positions it passed so then I can read them and draw the ball moves the same, restore its path.

I saw an example for binary file but it doesn't say much to me:

 // 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;
 }

Does it create the file automatically? Then where? And what about writing and reading points (X,Y,Z) ? Should I write it through binary bytes? or as points and the file makes it binary..?

You can write a point (X,Y,Z) to a binary file separating coordinates eg by colons, and points by semicolons:

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 << ';';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM