gpt4 book ai didi

c++ - 在单次调用c++中将整个二进制文件读入数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:56 25 4
gpt4 key购买 nike

我正在尝试将一个二进制文件读入一个结构数组

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;
}

但是读取导致段错误,我该如何解决?

最佳答案

这是错误的:

features.reserve( size/sizeof( FeaturePoint ));

你要将数据读入 vector ,你应该调整它的大小,而不仅仅是保留,像这样:

features.resize( size/sizeof( FeaturePoint ));

这也是错误的:

file.read( reinterpret_cast<char*>(&features),  size );

您不是在此处覆盖 vector 的数据,而是在覆盖结构本身,还有谁知道还有什么。应该是这样的:

file.read( reinterpret_cast<char*>(&features[0]),  size );

不过正如 Nemo 所说,这不太可能提高您的表现。

关于c++ - 在单次调用c++中将整个二进制文件读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6488847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com