2011-02-01 123 views
0

我試圖讀回一個字符串,我寫入二進制文件,但它給我的問題,我不知道發生了什麼事情。我打開和使用下面的代碼讀取我的文件:使用ifstream讀取和寫入二進制字符串的正確格式

ifstream input([filePath UTF8String], ios::in | ios::binary); 
int numStringBytes; 
input.read((char*)&numStringBytes, 4); 
char *names; 
input.read((char*)names, numStringBytes); 
input.close(); 

還有很多更重要的文件讀取代碼,但它是專有的,這是一個不斷崩潰的部分。它運行得很好加載前兩個文件,但是當我嘗試打開第三個文件時,它在input.read((char *)names,numStringBytes)處使用EXC_BAD_ACCESS崩潰;線。我認爲沒有任何理由認爲這會導致崩潰。任何想法的人?我正在使用以下代碼在VB.NET中編寫二進制文件:

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() 

回答

2

names需要分配。 您可以使用類似:

char *names = new char[ numStringBytes ]; 
input.read((char*)names, numStringBytes); 
... 
delete[] names; // don't forget to dealocate 

,或者更好的是,使用std::vector

std::vector<char> names(numStringBytes, 0); // construct a big enough vector 
input.read((char*)&names[ 0 ], numStringBytes); 
+0

謝謝,不知道我怎麼錯過了。 – Davido 2011-02-01 00:20:49