Ben*_*Ben 6 c++ binaryfiles ifstream
我试图将二进制文件读入结构数组
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;
};
Run Code Online (Sandbox Code Playgroud)
下面的代码可以工作,但是通过将每个新元素推送到数组上,一次完成这一个元素
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想通过立即读取整个数组加快速度,我认为应该看起来像下面这样
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;
}
Run Code Online (Sandbox Code Playgroud)
但是读取导致了seg故障,我该如何解决?
这是错误的:
features.reserve( size/sizeof( FeaturePoint ));
Run Code Online (Sandbox Code Playgroud)
您要将数据读入向量,您应该调整它的大小,而不仅仅是保留,如下所示:
features.resize( size/sizeof( FeaturePoint ));
Run Code Online (Sandbox Code Playgroud)
这也是错误的:
file.read( reinterpret_cast<char*>(&features), size );
Run Code Online (Sandbox Code Playgroud)
你不是在那里重写向量的数据,而是重写结构本身,以及谁知道还有什么。应该是这样的:
file.read( reinterpret_cast<char*>(&features[0]), size );
Run Code Online (Sandbox Code Playgroud)
但正如尼莫所说,这不太可能提高你的表现。