1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include<stdio.h>
class testObject
{
public:
/*
create a simple object to load and unload
*/
testObject(int inputNumber1, int inputNumber2)
{
number1=inputNumber1;
number2=inputNumber2;
}
/*
This constructor is suppose to create the object from data loaded from the file
*/
testObject(FILE *inputFile)
{
fread(&number1, sizeof(number1),1,inputFile);
fread(&number1, sizeof(number1),1,inputFile);
}
/*
This function is suppose to write out all the object fields for later retrieval
*/
void save(FILE *inputFile)
{
fwrite(&number1, sizeof(number1),1,inputFile);
fwrite(&number1, sizeof(number1),1,inputFile);
}
/*
This function is meant to be used in debugging to display the object field values
*/
void print(void)
{
printf("Number values: %d %d\n",number1,number2);
}
int number1;
int number2;
};
int main(int argc, char** argv)
{
//Make objects
testObject *pointer=new testObject(100,200);
testObject *pointer2=new testObject(400,500);
//Show objects are valid
pointer->print();
pointer2->print();
//Open binary file (should check for NULL, but this is test case)
FILE *file=fopen("testFile","wb");
//Save an integer with the number of objects, so it knows how many to retrieve later
int buffer=2;
fwrite(&buffer,sizeof(buffer),1,file);
//Save the objects
pointer->save(file);
pointer2->save(file);
//Close the file
fclose(file);
//Reopen the file for reading
file=fopen("testFile","rb");
//Read in the number of objects to retrieve
fread(&buffer,sizeof(buffer),1,file);
//Print the value to ensure it loaded correctly
printf("Buffer: %d\n",buffer);
//Retrieve the objects
for(int i=0;i<buffer;i++)
{
pointer=new testObject(file);
//print out the object values
pointer->print();
}
//Close the file
fclose(file);
return 0;
}
|