There are those occasions when users require to use a binary file to store information. My project required a structure array that contained 10,415 data records that I wanted to store in a file. The binary file IO routine did the trick. Reporpulating the array was accomplished with a simple read. No database access was required once the structure array was populated.
The structure in question is defined as follows:
[codesyntax lang=”cpp”]
struct user_record_area { long long id; string user_login; string user_pass; string user_nicename; string user_email; string user_url; string user_registered; string user_activation_key; long user_status; string user_display_name; };
[/codesyntax]
The array of structure in question had the following description.
[codesyntax lang=”cpp”]
user_record_area ura [10418];
[/codesyntax]
To read the array to a file using a code block like the one below will produce the desired results.
[codesyntax lang=”cpp”]
void extTools::readBin2() { ifstream myFile ("recs.bin", ios::in | ios::binary); // myfile.seekg() myFile.read ((char*) &ura, sizeof(ura)); if (!myFile) { ura[0].id = 22; } myFile.close(); }
[/codesyntax]
To write the array to a file using a code block like the one below will produce the desired results.
[codesyntax lang=”cpp”]
void extTools::writeBin2() { ofstream file ("recs.bin", ios::out|ios::binary); if (file.is_open()) { int size = sizeof(ura); file.write((char*) &ura, size); file.close(); } else cout << "Unable to open file"; }
[/codesyntax]
Once the file is populated to retrieve data records is a snap (without DBMS access);
Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.