Reading and Writing Entire Structures
This is an OLD tutorial I wrote back in 2004 when I was doing HL1 mods. I had only been writing hardcore C++ for about 2 years at that point, so forgive any strange-ness to this article. Taken from http://articles.thewavelength.net/467/
This tutorial is simple, and very straightforward. Most programmers know by now that it is possible to read and write entire data structures to files binarily (sp?). I did not know this until a few weeks ago, and I’ve been doing this stuff for years (shows where I’ve been, hehe). All this tutorial really needs is fopen, fread, fwrite, and fclose. So… here goes nothing:
First, include the right files:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>Then create your struct (file format):
struct DATA
{
unsigned char data1[1024]; // big values are cool!
bool data2;
unsigned short data3;
unsigned long data4;
};Now we start the main driver (yes, I called it a driver back then…. sorry), which handles everything:
int main( int argc, char *argv[] )
{
// create some data
DATA *pData = new DATA;
// since data1's array size is 1024, try and put as much data into it as you can
strcpy(pData->data1, "Hello from data1 of the DATA struct!!!!");
pData->data2 = true;
pData->data3 = 293742346876345; // jibberish number
pData->data4 = 5994572987429687657589579847967495; // jibberish number// write the data structure to a file
FILE *pFile = fopen("data.txt", "wb"); // notice the "wb" for write in binary mode?
fwrite(pData, sizeof(struct DATA), 1, pFile); // third param is always 1 (at least everything that I've seen)
fclose(pFile); // close the filedelete pData; // delete the structure (we don't want leaks)
// read the file BACK into memory
DATA *pRead = new DATA; // create another instance of the structure for reading
pFile = fopen("data.txt", "rb"); // note the "rb" for read binary mode
fread(pRead, sizeof(struct DATA), 1, pFile); // this is almost exactly the same as the fwrite call
fclose(pFile); // close the file again// output the struct data
printf("%s\n%i\n%i\n%i\n", pRead->data1, pRead->data2, pRead->data3, pRead->data4);delete pRead; // again, no memory leaks
return 0; // any function (declared as int) returns a value
}This will output the same data we put INTO the struct in the main driver, to the data that was read OUT of the struct into the console.
NOTE: Open the file in notepad once, notice how it looks nothing like plain text?![]()