输出一个用二进制文件C ++编写的double

时间:2016-10-03 20:38:12

标签: c++ file fstream bin seekg

我有一个名为“obj”的类,它有两个数据类型,一个是int,一个是double。我试图只读第三个对象,但似乎无法弄明白。在我将其中一个数据类型更改为double之前,它正在工作。我觉得这与类型转换有关。总结一下,我无法在文件被写入后只输出第三个对象。有什么建议吗?

#include<iostream>
#include<fstream>

using namespace std;

class Data {

public:
    int num1;
    double num2;

    Data() {}
    ~Data() {}
    void setData();
    void getData();
};

void Data::getData()
{
    cout << "Enter first number: ";
    cin >> num1;

    cout << "Eneter second number: ";
    cin >> num2;

}









#include "class.h"


    const int SIZE = 5;
    int main()
    {

        Data obj[SIZE];

        for (int i = 0; i < SIZE; i++)
        {
            cout << "Enter numbers of object " << i+1 << endl;

            obj[i].getData();

        }


        ofstream outFile;
        outFile.open("C:\\Users\\juan\\Desktop\\26.bin", ios::out | ios::binary);

        for (int i = 0; i < SIZE; i++)
        {

            outFile.write(reinterpret_cast<char *> (&obj[i].num1), sizeof(obj[i].num1));
            outFile.write(reinterpret_cast<char *> (&obj[i].num2), sizeof(obj[i].num2));

        }

        cout << "Writing to file...." << endl;

        outFile.close();

        ifstream inFile;
        inFile.open("C:\\Users\\juan\\Desktop\\26.bin", ios::in | ios::binary);

        for (int i = 0; i < SIZE; i++)
        {
            inFile.read(reinterpret_cast<char *> (&obj[i].num1), sizeof(obj[i].num1));
            inFile.read(reinterpret_cast<char *> (&obj[i].num2), sizeof(obj[i].num2));



        }

        for (int i = 0; i < SIZE; i++)
        {
            cout << obj[i].num1 << endl;
            cout << obj[i].num2 << endl;
            cout << endl << endl;
        }

        inFile.close();

        Data third;
        fstream seekfile;


        seekfile.open("C:\\Users\\juan\\Desktop\\26.bin", ios::in | ios::binary);

        seekfile.seekg(2 * sizeof(Data), ios::beg);

        seekfile.read(reinterpret_cast<char *> (&third.num1), sizeof(third.num1));
        seekfile.read(reinterpret_cast<char *> (&third.num2), sizeof(third.num2));

        cout << endl << endl;
        cout << third.num1 << endl;
        cout << third.num2 << endl;

        seekfile.close();





    }

1 个答案:

答案 0 :(得分:0)

问题在于sizeof(Data) 不是 sizeof(int) + sizeof(double)的总和,因此seekfile.seekg(2 * sizeof(Data), ios::beg)不正确。此

seekfile.seekg(2 * (sizeof(third.num1) + sizeof(third.num2))

应该解决问题。

请注意,由于填充,sizeof(Data)大于其组件的总和。有关详细信息,请参阅此处:

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

另请注意,如果您将num2重新定义为int,则无需填充,在这种情况下,您的原始代码可以正常运行。