开发者

read from file to array C++

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->Execu开发者_运维问答te()) {
    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 vector type. 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:

#include <vector> // so we can actually use vectors

... // program code here

// here's a basic loop which fills a vectors with the numbers 1 to 99.
std::vector<unsigned char> myVec;
while( there_is_stuff_to_read )
{
    myVec.push_back(get_next_element());
}

Of course, the loop would involve whatever file reading classes you use. The key is the push_back method 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:

unsigned char * arr = &myVec[0];

Then you can use arr as 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:

unsigned char * arr = new unsigned char[myVec.size()];
std::copy(myVec.begin(), myVec.end(), arr);

Just make sure you include the standard <algorithm> header.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜