i wanna read from file to array of unsigned char in RAD studio 2010, i have an example,but i need to read to array size of file. Sorry my english
void __fastcall TForm1::ChooseFileClick(TObject *Sender)
{
TOpenDialog *od = new TOpenDialog(this);
if (od->Execute()) {
TFileStream *fs = new TFileStream(od->FileName,fmOpenRead);
fs->Position = soFromBeginning;
TMemo *m = new TMemo(this);
m->Parent = this;
m->Lines->LoadFromStream(fs);
delete fs;
fs = NULL;
}
delete od;
od = NULL;
}
While I’m not sure of your exact intent, I can tell you this: don’t use a raw array!
In C++, we have the
vectortype. A vector is very similar to an array, but you can keep adding elements to it. If it gets full, it makes itself bigger. (In actual fact, a vector is simply a wrapper for an array. When it is filled up, it creates a larger array, copies the element to the new array, and then discards the original array).When using
vector, you’re code follows this style:Of course, the loop would involve whatever file reading classes you use. The key is the
push_backmethod which adds elements to the vector.If other portions of your code rely specifically on using an array of unsigned char, then you can fill the vector, and the use this line of code as necessary:
Then you can use
arras your usual unsigned char array. Just make sure that you don’t hang on this pointer after adding more elements to the vector. It isn’t guaranteed to remain a valid pointer to the start of the vector’s internal array (since the vector reallocates its internal array).The previous line of code doesn’t create a whole new array. If you want a genuine copy of the internal contents of the vector, you can use something like:
Just make sure you include the standard <algorithm> header.