I'm trying to read back a string that I wrote into a binary file, but it's giving me problems and I don't know what's going on. I open and read my file using the code below:
ifstream input([filePath UTF8String], ios::in | ios::binary);
int numStringBytes;
input.read((char*)&numStringBytes, 4);
char *names;
input.read((char*)names, numStringBytes);
input.close();
There is a lot more to the file reading code, but it's proprietary and this is the part that keeps crashing. It runs fine loading the first two files, but when I try to open a third file, it crashes with EXC_BAD_ACCESS at the input.read((char*)names, numStringBytes); line. I don't see any reason that this should crash. Any ideas anyone? I'm writing the binary files in VB.NET using the below code:
Dim myFS As New FileStream(savePath, FileMode.Create)
Dim encoding As New System.Text.UTF8Encoding()
Dim stringBytes() As Byte = encoding.GetBytes("++string")
Dim stringByteSize(0) As Integer
stringByteSize(0) = stringBytes.Count
Dim stringCountBytes(3) As Byte
Buffer.BlockCopy(stringByteSize, 0, stringCountBytes, 0, stringCountBytes.Count)
myFS.Write(stringCountBytes, 0, stringCountBytes.Length)
myFS.Write(stringBytes, 0, stringBytes.Length)
myFS.Close()
names
needs to be allocated.
You can use something like:
char *names = new char[ numStringBytes ];
input.read((char*)names, numStringBytes);
...
delete[] names; // don't forget to dealocate
or, better yet, use a std::vector
:
std::vector<char> names( numStringBytes, 0 ); // construct a big enough vector
input.read((char*)&names[ 0 ], numStringBytes);