This works on Dev-C++ though I couldn't get it to work on VC6 with similar syntax the other night when I was working on this. I'll retry later with VC6 to see if I screwed up somehow earlier (not an impossibility), or if there's a difference between VC6 and DevC++.
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Student1
{
string name;
int age;
};
void write(ofstream & fout, Student1 * s1array[], int size )
{
int len;
int i;
for(i = 0; i < size; ++i)
{
len = (s1array[i]->name).length();
fout.write((char *) &len, sizeof(int));
fout.write((char *) &(s1array[i]->name), len);
fout.write((char *) &(s1array[i]->age), sizeof(int));
}
}
void read(ifstream & fin, Student1 * s1array2[], int size)
{
int i;
int len;
for(i = 0; i < size; ++i)
{
fin.read((char *) &len, sizeof(int));
fin.read((char *) &(s1array2[i]->name), len);
fin.read((char *) &(s1array2[i]->age), sizeof(int));
}
}
int main(int argc, char *argv[])
{
Student1 s;
Student1 s1;
s.name = "tom";
s.age = 19;
Student1 * s1array[1];
s1array[0] = &s;
int size = 1;
ofstream fout("binaryFileWriting.txt");
write(fout, s1array, size);
fout.close();
Student1 * s1array2[1];
s1array2[0] = new Student1;
ifstream fin("binaryFileWriting.txt");
read(fin, s1array2, size);
fin.close();
cout << s1array2[0]->name << ' ' << s1array2[0]->age << endl;
delete s1array2[0];
system("PAUSE");
return 0;
}