[英]read entire binary file into an array in single call c++
我試圖將二進制文件讀入結構數組
struct FeaturePoint
{
FeaturePoint (const int & _cluster_id,
const float _x,
const float _y,
const float _a,
const float _b
) : cluster_id (_cluster_id), x(_x), y(_y), a(_a), b(_b) {}
FeaturePoint (){}
int cluster_id;
float x;
float y;
float a;
float b;
};
下面的代碼可以工作,但是通過將每個新元素推送到數組上,一次完成這一個元素
void LoadImageFeaturesFromBinaryFile(const char * FileName, std::vector<FeaturePoint>& features )
{
char strInputPath[200];
strcpy (strInputPath,"/mnt/imagesearch/tests/");
strcat (strInputPath,FileName);
strcat (strInputPath,".bin");
features.clear();
ifstream::pos_type size;
ifstream file (strInputPath, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
cout<< "this file size is : "<<size<<" for "<<strInputPath<<" " <<sizeof( FeaturePoint )<<endl;
file.seekg (0, ios::beg);
while (!file.eof())
{
try
{
FeaturePoint fp;
file.read( reinterpret_cast<char*>(&fp), sizeof( FeaturePoint ) );
features.push_back(fp);
}
catch (int e)
{ cout << "An exception occurred. Exception Nr. " << e << endl; }
}
sort (features.begin(), features.begin()+features.size(),CompareClusterIndexes);
file.close();
}
}
我想通過立即讀取整個數組加快速度,我認為應該看起來像下面這樣
void LoadImageFeaturesFromBinaryFile(const char * FileName, std::vector<FeaturePoint>& features )
{
char strInputPath[200];
strcpy (strInputPath,"/mnt/imagesearch/tests/");
strcat (strInputPath,FileName);
strcat (strInputPath,".bin");
features.clear();
ifstream::pos_type size;
ifstream file (strInputPath, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
file.seekg (0, ios::beg);
features.reserve( size/sizeof( FeaturePoint ));
try
{
file.read( reinterpret_cast<char*>(&features), size );
}
catch (int e)
{ cout << "An exception occurred. Exception Nr. " << e << endl; }
sort (features.begin(), features.begin()+features.size(),CompareClusterIndexes);
file.close();
}
else cout << strInputPath<< " Unable to open file for Binary read"<<endl;
}
但是讀取導致了seg故障,我該如何解決?
這是錯的:
features.reserve( size/sizeof( FeaturePoint ));
您將要將數據讀入向量,您應該調整它的大小,而不僅僅是保留,如下所示:
features.resize( size/sizeof( FeaturePoint ));
這也是錯的:
file.read( reinterpret_cast<char*>(&features), size );
你沒有在那里寫過矢量數據,你要覆蓋結構本身,以及誰知道還有什么。 它應該是這樣的:
file.read( reinterpret_cast<char*>(&features[0]), size );
就像Nemo說的那樣,這不太可能改善你的表現。
你的features
類型是一個std :: vector,你將它包裝成char。 類型矢量不是數組。
我想你想要的
file.read( reinterpret_cast<char*>(&features[0]), size );
您還需要確保size
是sizeof(FeaturePoint)
的倍數。 否則,你會讀得太多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.