我想收縮與浮點值大的文本文件轉換成一個二進制.dat文件的大小,所以就用(在C++):二進制.dat文件問題
// the text stream
std::ifstream fin(sourceFile);
// the binary output stream
std::ofstream out(destinationFile, std::ios::binary);
float val;
while(!fin.eof())
{
fin >> val;
out.write((char *)&val,sizeof(float));
}
fin.close();
out.close();
然後,我想從rpeviously創建的二進制文件中讀取所有的浮點值到一個浮點值數組中。 但是,當我嘗試從這個文件中讀取我在最後一行代碼(閱讀過程中)得到一個異常:
// test read
std::ifstream fstream(destinationFile, std::ios::binary);
__int64 fileSize = 0;
struct __stat64 fileStat;
if(0 == _tstat64(destinationFile, &fileStat))
{
fileSize = fileStat.st_size;
}
//get the number of float tokens in the file
size_t tokensCount = fileSize/sizeof(float);
float* pBuff = new float[tokensCount];
fstream.read((char*)&pBuff, tokensCount * sizeof(float));
我在做什麼錯?
你是對的,但如果我寫 fstream.read(的static_cast(PBUFF),tokensCount *的sizeof(浮動)); 它仍然不能編譯... –
melculetz
2010-02-09 12:27:28
對不起,我只用char * pBuff對其進行了測試,但當pBuff是任何其他類型時,它不起作用。有什麼方法可以讓我從這些upvotes中獲得的代表回覆? – Manuel 2010-02-09 12:53:30
別擔心。儘管'reinterpret_cast'在這裏可能更適合,不管怎麼說,使用C++風格的類型轉換都是很好的建議。 – 2010-02-10 11:35:45