Writing/reading struct arrays
I've got a simple struct (myStruct), with a few char arrays, and I'm trying to write it an array of type myStruct to a file, in order to later be able to retrieve it from that file, back into an array of type myStruct. What would be the best way to go about this? I've experimented a bit with ifstream/ofstream, and a bit with CreateFile, WriteFile, ReadFile, etc.. in winbase.h, and I can't get it to work properly...Any help would be greatly appreciated.
Re: Writing/reading struct arrays
Quote:
Originally posted by Zorander
I've got a simple struct (myStruct), with a few char arrays, and I'm trying to write it an array of type myStruct to a file, in order to later be able to retrieve it from that file, back into an array of type myStruct. What would be the best way to go about this? I've experimented a bit with ifstream/ofstream, and a bit with CreateFile, WriteFile, ReadFile, etc.. in winbase.h, and I can't get it to work properly...Any help would be greatly appreciated.
Code:
#include <iostream>
#include <fstream>
struct Test
{
char a[10];
char b[10];
};
std::ostream& operator << (std::ostream& str, const Test& x)
{
str << x.a << '\n' << x.b;
return str;
}
std::istream& operator >> (std::istream& str, Test& x)
{
str >> x.a >> x.b;
return str;
}
// Test
using namespace std;
int main()
{
Test A;
strcpy(A.a,"Test1");
strcpy(A.b,"Test2");
// Test to cout / cin
cout << A << endl;
cout << "Input ";
cin >> A;
cout << A << endl;
// Test to file
ofstream f("c:/test");
f << A;
f.close();
ifstream f2("c:/test");
f2 >> A;
}
Regards,
Paul McKenzie