2010-07-15 83 views
1

我正在使用cstdio (stdio.h)從二進制文件讀取和寫入數據。由於遺留代碼,我必須使用這個庫,並且它必須與Windows和Linux跨平臺兼容。我有一個FILE* basefile_,我用它來讀取變量configLabelLengthconfigLabel,其中configLabelLength告訴我有多少內存分配給configLabel我可以使用無指針的fread讀取動態長度變量嗎?

unsigned int configLabelLength; // 4 bytes 
char* configLabel = 0;   // Variable length 

fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_); 
configLabel = new char[configLabelLength]; 
fread(configLabel,1, configLabelLength,baseFile_); 

delete [] configLabel; // Free memory allocated for char array 
configLabel = 0; // Be sure the deallocated memory isn't used 

有沒有辦法在configLabel不使用指針讀?例如,有一種解決方案,我可以使用C++矢量庫或者我不必擔心指針內存管理的問題。

+0

有什麼理由不使用C++的文件流嗎? – Cogwheel 2010-07-15 19:19:37

+0

@Cog:在問題的頂部。 :)和+1尋求使用向量。 – GManNickG 2010-07-15 19:21:13

+0

@Cogwheel由於遺留代碼,我不得不使用'cstdio(stdio.h)'。我知道這並不理想。 – Elpezmuerto 2010-07-15 19:21:26

回答

5

只要做到:

unsigned int configLabelLength; // 4 bytes* 
fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_); 

std::vector<char> configLabel(configLabelLength); 
fread(&configLabel[0], 1, configLabel.size(), baseFile_); 

在一個矢量中的元素是連續的。


*我想你知道,unsigned int是沒有必要總是4個字節。如果您注意到您的實施細節沒有問題,但是如果您採用Boost的cstdint.hpp並僅使用uint32_t,則會更容易一些。

+0

@Gman ......那個假設是正確的。由於遺留代碼,其他不太熟練/有經驗的用戶將使用此代碼,我正在盡我所能保持代碼的可讀性。我真的很喜歡boost,並在其他地方實現它,但我試圖對變量實施提升。 我們的ICD專門使用術語'unsigned int',所以我想嘗試與其他用戶的ICD匹配。 :p – Elpezmuerto 2010-07-15 19:29:03

+0

與您的4字節評論大同意。二進制文件和網絡代碼應始終使用具有指定大小,對齊和字節順序的對象。外匯,我使用名爲le_uint32_t的C++結構使代碼在PowerPC上以英特爾二進制格式工作。 – 2010-07-15 19:31:40

相關問題