Hi !
I would like to ask your help. Since days, I am reading fstream tutorial in tutorials section as I am trying to put together 3routines:
1., Can write a structure to a file. (ButtonClick1)
2., Can tell how many records in the file (ButtonClick2)
3, Can read back the structure from the file. (ButtonClick3)
I thought is simple but I can not get it to work.
- I mean I had created the structure in the main header like this :
private: // User declarations
struct WebSites
{
AnsiString name;
int level;
int image_index;
int selected_index;
};
- And the 3 routines to read and write struct to files :
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
WebSites p_Data;
p_Data.name = Edit1->Text;
p_Data.level = StrToInt(Edit2->Text);
p_Data.image_index = StrToInt(Edit3->Text);;
p_Data.selected_index = StrToInt(Edit4->Text);;
fstream binary_file("c:\\test.dat",ios::out|ios::text|ios::app);
binary_file.write(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
binary_file.close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
WebSites p_Data;
int fl_sz;
int total_no_rec;
fstream binary_file("c:\\test.dat",ios::text|ios::in);
binary_file.seekg(0,ios::end);
fl_sz = binary_file.tellg();
total_no_rec = fl_sz/sizeof(WebSites);
Memo1->Lines->Add(total_no_rec);
binary_file.close();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
WebSites p_Data;
fstream binary_file("c:\\test.dat",ios::text|ios::in);
binary_file.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
Memo1->Lines->Add(p_Data.name);
binary_file.close();
}
//---------------------------------------------------------------------------
But it is not working consequently. I mean several times cause general error
fault, or not reading the file or it seems the data written is not even
correct.
So I am completely lost. Could somebody help me please ?
Many thanks in advance,
Moore