c++ – Incorrect reading of binary files

Question:

I needed to read three binaries with a given structure. Their structures are as follows: File 1:

struct data_star 
{
    long  NSAO;
    long alpha; 
    long beta;
    short ualpha;
    short ubeta;
    unsigned char mv;
    char sp;
};

I read it like this:

data_star d;
QVector <data_star> vec;
ifstream in(filename.toUtf8().constData(),ios::binary);
while(in.read((char*)&d,sizeof(data_star)))// считываем в вектор структур
{
    vec.push_back(d);
}
in.close();

It was considered great, without any problems.

File 2:

struct sector
{
    float alpha_c;
    float beta_c;
    long count_in_sector;
    long shift;
};

I read it the same way:

sector sectr;
QVector <sector> vec_s;
ifstream in_1("C:\\Users\\Shmeisser\\Documents\\catalog_v2\\catalog\\NEW_642.CAT",ios::binary);
while(in_1.read((char*)&sectr,sizeof(sector)))// считываем каталог в вектор структур
{
    vec_s.push_back(sectr);
}

But here it reads completely incorrectly, having looked at the record in the structure in the debug, I noticed that in part, the data is written to the structure correctly, that is, let's say the first line read had correct values ​​in the first three structure elements and incorrect in the fourth, etc.

3 File: (consists of a short element)

short num;
QVector<short> new_numn;
ifstream in_2("C:\\Users\\Shmeisser\\Documents\\catalog_v2\\catalog\\NEW_NUMN.CAT",ios::binary);
while(in_2.read((char*)&num,sizeof(short)))// считываем каталог в вектор
{
    new_numn.push_back(num);
}

Here it is also written incorrectly, but it is already difficult to say partially or completely. So, the point is that once these binaries were accurately read, albeit with the stdio.h library. Perhaps they were beaten when I copied them to my flash drive, but something I doubt it. In general, I would like to clarify, are there any other options why the files are being read incorrectly? (before I turn to the person who gave me these files, I don’t want to make myself look like an idiot :)). And also, if that the first and the second structure are aligned by 1 byte, so this reason disappears.

Answer:

When compiling a program, the compiler aligns structures by default, and the alignment can be different on different platforms with different compilers.

struct sector
{
  float alpha_c;
  float beta_c;
  long count_in_sector;
  long shift;
};

Such a structure can be either 16 bytes or 24 bytes in size.

But you can try __atributte__((packed)) it will __atributte__((packed)) compiler not to align the structure

struct sector
{
 float alpha_c;
 float beta_c;
 long count_in_sector;
 long shift;
} __atributte__((packed));
Scroll to Top