Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Good day,

I have a block of code that reads structures and related character strings from a binary file. The length of the character string is defined within the structure read immediately prior.

Currently, I am reading the string one character at a time but I am positive that something better with dynamic character arrays.

The structures are pretty basic, a few numbers and the length of the string being one.

C#
ifstream in_file("(path)\\zTEST.dat", ios::binary);
if ( !in_file.is_open() ) {
     MessageBox::Show("File failed to open.");
  } else {
     sst = "";

     SFE_structure r;
     in_file.read(reinterpret_cast<char*>(&r), sizeof(SFE_structure));
     char coop;
     MessageBox::Show("numEntries=" + r.numEntries,"length of string");
     for (i=0;i<r.numEntries;i++){
          coop = in_file.get();
          sst = sst + coop;
     }
    this->textParentID->Text = gcnew String(sst.c_str());
 (***)
}

This works to read the characters in. It just seems that it might be inefficient, so I thought I would look at doing a dynamic array:
C#
in_file.read(reinterpret_cast<char*>(&r), sizeof(SFE_structure));
                    sst = "";

                    MessageBox::Show("numEntries=" + r.numEntries,"length of string");
                    char * tmpDynamicArray = new char[r.numEntries];
                    in_file.read(tmpDynamicArray, r.numEntries);
                    sst = tmpDynamicArray;
                    delete [] tmpDynamicArray;
                    this->textSelfID->Text = gcnew String(sst.c_str());

(***)
}


It works but there are trailing characters on the character array. One instance, for example, is a two character pairing. When I dimension the array tmpDynamicArray based upon the r.numEntries (2), I get
"x>x>S"

(there are some of the block / boxy characters that aren't showing in the <pre> code area)

When it reads the dynamic array, it does take the two proper characters but the remaining characters remain. (Size becomes 9 in debug mode, in release mode it looks longer but I cannot tell...)

If I do a "sizeof(tmpDynamicArray)" it shows 4 in release and debug.


Coming from a Pascal / VB (not even .NET) background, so the string conversions are a real treat... trying to learn.
Posted

1 solution

Think I've solved it...
forced the null at the end of the expected size by putting in

C#
char * tmpDynamicArray = new char[r.numEntries + 1];
in_file.read(tmpDynamicArray, r.numEntries);
tmpDynamicArray[ r.NumEntries ] =  '\0';
sst = tmpDynamicArray;


and it seems okay... testing further.


If I am way off base, redirection would be greatly appreciated.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900