Originally Posted by
tabstop
If you write (in binary form) a pointer, then all you will get is the value of the pointer, not the string. You will have to write the contents of the pointer (plus the null character or some other I'm-done-here signal) at the minimum. Reading that file back in could then be a little obnoxious, since you won't know ahead of time how big your string needs to be -- all you can do is read a character at a time until you find your I'm-done-here signal and stop.
Thank you very much for your reply! Though it wasn't (exactly) what I was hoping for, it most definitely helped!!
I can see that I was perhaps going about it incorrectly, the wrong way &/or didn't have all the info I needed. Your comment though really helped me help myself after spending some more time trying to understand these particular aspects.
I managed to figure this out (I hope) & this is what I managed to come up with;
(I'm guessing there'd be a more better/efficient way to do something like this ?)
Code:
#include <sys/stat.h>
struct stat results;
#include <fstream>
#include <iostream>
using namespace std;
class Data
{
public:
char m_Member1;
int m_Member2;
int m_Member3;
char m_Member4;
string m_Member5;
bool m_Member6;
};
int main()
{
int pos = 0;
Data xData;
xData.m_Member1 = 'a';
xData.m_Member2 = 123;
xData.m_Member3 = 789;
xData.m_Member4 = 'z';
xData.m_Member5 = "This is a string";
xData.m_Member6 = 1;
Data *yData;// = new Data[10];
char *filename = "Reading&WritingComplexData1.txt";
fstream file (filename, ios::out|ios::in | ios::binary);
file.write((char*)&xData, sizeof(xData));
if( file.is_open())
{
cout<<"File is open."<<endl;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(char)); //for some reason though this now creates a warning, but it didn't before.
cout<<(char)yData<<endl;
pos = 4;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(int));
cout<<(int)yData<<endl;
pos = 8;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(int));
cout<<(int)yData<<endl;
pos = 12;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(char)); //warning r.e. same with last char
cout<<(char)yData<<endl;
pos = 16;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(string));
cout<<(char*)yData<<endl;
pos = 20;
file.seekp(pos);
file.seekg(pos);
file.read((char*)&yData,sizeof(bool));
cout<<(bool)yData<<endl;
}
cin.get();
}