2010-07-15 82 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

相关问题