c ++从/到二进制文件的读/写类

时间:2016-05-04 22:07:29

标签: c++ serialization binaryfiles

我需要将一个类写入二进制文件,然后我需要将其读回来。

我有TriangleBinaryFile个类,以及其他一些类。我不确定我写错了还是读错了。读取时发生错误。调试后,我认为它为我的私有变量获取了不适当的数据。如果有人能就如何使其正常运作给我一些建议,我将非常高兴。

我不确定是否应该粘贴整个代码,所以我会给你一小段代码。以防万一,这是我的源代码的下载链接:

https://my.pcloud.com/publink/show?code=XZJ7CYZbsLWLglqV5p83csijcEUTFqqpM3k

我是编程新手,我不会说英语,所以我提前为我的错误道歉。

class Point
{
private:
    int x;
    int y;
};

class Figure
{
private:
    string name;
    string type;
};

class Triangle: public Figure
{
private:
    Point p1, p2, p3;
};

class BinaryFile
{
private:
    string FileName;
    fstream File;
public:
    //...
    void AddNewFigure(istream& stream)
    {       
        File.open(this->FileName, ios::binary | ios::app);
        if(!this->File)
        {
            cerr<<"File error <"<<this->FileName<<">\n";
            exit(1);
        }
        Triangle fig;
        fig.MakeNewFigure(stream);
        File.write((char*)&fig, sizeof(Triangle));
        File.close();
    }

    Triangle GetTriangle()
    {
        Triangle trig;
        Point p;
        string str(""); int x(0);
        File.open(this->FileName, ios::binary | ios::in);
        if(!this->File)
        {
            cerr<<"File error <"<<this->FileName<<">\n";
            exit(1);
        }
        File.read((char*)&trig, sizeof(Triangle));
        File.close();
        return trig;
    }
};

3 个答案:

答案 0 :(得分:1)

由于源代码较大且数据文件丢失,重现错误并不容易。但快速检查显示您使用bloc操作读取和写入二进制数据:

    Triangle trig; 
    ...
    File.read((char*)&trig, sizeof(Triangle));

不幸的是,只有当您要保存/加载的对象属于trivially copyable的类时,这种方法才有效,如下面的代码所示:

if (is_trivially_copyable<Triangle>::value) 
    cout << "Triangle is  trivially copyable" << endl; 
else cout << "Triangle is not trivially copyable" << endl; 

因此,您必须按字段序列化对象内容写入字段,而不是使用bloc操作。这个FAQ on serialization应该可以帮助您考虑替代方案。

答案 1 :(得分:1)

答案取决于您是否只是为了了解文件的工作方式或者保存到文件是否只是偶然的而且您不关心它是如何工作的。

如果您只想获取要保存和恢复的内容,而您不关心它是如何工作的,那么请使用第三方库。他们中有很多人。

如果您想学习如何读取和写入文件,那么您将需要自己进行读写功能。我已经制作了一个示例程序来解释它是如何工作的:

#include <string>
#include <fstream>
#include <iostream>

class Point
{
private:
    int x;
    int y;
public:
    Point():x(0),y(0){}
    Point(int x,int y):x(x),y(y){}

    void write(std::ostream& f)
    {
        // We can just write out the bytes for x and y because
        // they are primitive types stored in the class
        f.write( (char*)&x, sizeof(x) );
        f.write( (char*)&y, sizeof(y) );
    }
    void read(std::istream& f)
    {
        // We can just read the bytes directly into x and y because
        // they are primitive types stored in the class
        f.read( (char*)&x, sizeof(x) );
        f.read( (char*)&y, sizeof(y) );
    }
};

class Figure
{
private:
    std::string name;
    std::string type;
public:
    Figure(){}
    Figure(std::string name,std::string type):name(name),type(type){}

    void write(std::ostream& f)
    {
        size_t size;

        // we need to store the data from the string along with the size
        // because to restore it we need to temporarily read it somewhere
        // before storing it in the std::string (istream::read() doesn't
        // read directly to std::string)

        size = name.size();
        f.write( (char*)&size, sizeof(size_t) );
        f.write( (char*)name.c_str(), size );

        size = type.size();
        f.write( (char*)&size, sizeof(size_t) );
        f.write( (char*)type.c_str(), size );
    }
    void read(std::istream& f)
    {
        size_t size;
        char *data;

        // when we read the string data we need somewhere to store it
        // because we std::string isn't a primitive type.  So we read
        // the size, allocate an array, read the data into the array,
        // load the std::string, and delete the array

        f.read( (char*)&size, sizeof(size) );
        data = new char[size+1];
        f.read( data, size );
        data[size]='\0';
        name = data;
        delete data;

        f.read( (char*)&size, sizeof(size) );
        data = new char[size+1];
        f.read( data, size );
        data[size]='\0';
        type = data;
        delete data;
    }
};

class Triangle: public Figure
{
private:
    Point p1, p2, p3;
public:
    Triangle(){}
    Triangle(Point x,Point y,Point z,Figure f):p1(x),p2(y),p3(z),Figure(f){}


    void write(std::ostream& f)
    {
        // First write the base class then write the members of this class
        Figure::write(f);
        p1.write(f);
        p2.write(f);
        p3.write(f);
    }
    void read(std::istream& f)
    {
        // First read the base class then read the members of this class
        Figure::read(f);
        p1.read(f);
        p2.read(f);
        p3.read(f);
    }
};

class BinaryFile
{
private:
    std::string FileName;
    std::fstream File;
public:
    BinaryFile(std::string FileName) : FileName(FileName) {};
    void WriteTriangle()
    {
        File.open(FileName, std::ios::binary | std::ios::out);
        if(!File)
        {
            std::cerr<<"File error <"<<FileName<<">\n";
            exit(1);
        }
        Triangle trig({1,2},{3,4},{5,6},{"name","type"}); // something new
        trig.write(File);
        File.close();
    }

    Triangle ReadTriangle()
    {
        File.open(FileName, std::ios::binary | std::ios::in);
        if(!File)
        {
            std::cerr<<"File error <"<<FileName<<">\n";
            exit(1);
        }
        Triangle trig; // default values
        trig.read(File);
        File.close();
        return trig;
    }
};

main()
{
    BinaryFile bin("file.bin");
    bin.WriteTriangle();
    Triangle trig = bin.ReadTriangle();
    // at this point trig has the values we stored
    return 0;
}

答案 2 :(得分:0)

您要查找的是序列化应保存到文件的类/数据。有几个库已针对此进行了时间和内存消耗的优化。你介意使用第三方图书馆吗?

如果没有,请查看例如boost serializationcereal或甚至Google ProtoBuf。如果您使用的是C ++ 11,我认为Cereal是一个很好的开始。

如果您想编写自己的序列化,则必须考虑每个具有动态大小的对象(例如字符串),您还需要保存对象&#39;文件大小。欲了解更多信息,请点击此处:

https://stackoverflow.com/a/11003590/5874704