HI
I am trying to write and read to file. I am experimenting with a small piece of code before going onto my main program.
I am simply trying to write a float variable and a String variable to file using fstream.
The variables are
float version;
Edit1->Text (this is c++ builder edit box) (text is set to "edit1" for this test)
The code I have so far is:
For saving the two variables:
AnsiString fn = SaveDialog1->FileName; //save filename into a format fstream can use
fstream file(reinterpret_cast<char*>(&fn),ios::out|ios::binary);//open file
file.write(reinterpret_cast<char *>(&version),sizeof(float));//write version
//now load edit1 into the file
int length=Edit1->Text.Length()+1;//get length of string
char *cp = new char[ Edit1->Text.Length() + 1 ];
StrCopy( cp, Edit1->Text.c_str() );//copy string to char for fstream
file.write(cp,length);//now write string
file.close();
For Loading the two variables
AnsiString fn = OpenDialog1->FileName;
fstream file(reinterpret_cast<char*>(&fn),ios::binary|ios::in);//open file
file.read(reinterpret_cast<char *>(&version),sizeof(float));//read in version
char cp[6];//create array for recieving string in the format of char array
file.read(cp,length);//read in array
Edit1->Text=cp;//write the value back to test
file.close();
<< moderator edit: added [code][/code] tags >>
I have two problems with this. First I have to set char cp[6] in the load function to 6 manually, (which is the size of the text+1). How can I do this in runtime without knowing what length the user will write. I have tried setting char cp[256], but when I put this back to Edit1->Text I just get garbage.
Second problem. This works fine if I only run Load function once. If i run load function again I then get garbage going into Edit1->Text. If i close program, run again and then run load function its fine (untill i run function again)
Any ideas??
regards
Nath