Tôi cố gắng để đọc một tập tin nhị phân vào một mảng của cấu trúcđọc toàn bộ tập tin nhị phân thành một mảng trong single gọi 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;
};
Các mã bên dưới công trình nhưng không một yếu tố này cùng một lúc, bằng cách đẩy mỗi yếu tố mới vào một mảng
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();
}
}
tôi muốn tăng tốc độ nó lên bằng cách đọc toàn bộ mảng trong cùng một lúc, mà tôi nghĩ nên tìm một cái gì đó như sau
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;
}
Nhưng đọc được gây ra một lỗi seg, làm thế nào để sửa lỗi này?
Tôi dự đoán rằng khi bạn làm việc này, bạn sẽ ngạc nhiên về mức độ cải thiện hiệu suất của nó. – Nemo
Làm cho bạn một ưu tiên và sử dụng 'std :: string' thay vì' strcat'. –