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

时间:2011-06-27 05:17:35

标签: 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;
};

下面的代码有效但通过将每个新元素推送到数组

,一次完成这一个元素
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故障,我该如何解决?

3 个答案:

答案 0 :(得分:3)

这是错误的:

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所说,这不太可能改善你的表现。

答案 1 :(得分:0)

你的features类型是一个std :: vector,你把它封装成char。类型矢量不是数组。

答案 2 :(得分:0)

我想你想要

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

您还需要确保sizesizeof(FeaturePoint)的倍数。否则,你会读得太多。

相关问题