从c ++中的二进制文件中读取结构

时间:2013-05-25 22:13:49

标签: c++ file file-io

所以我试图从我写的二进制文件中读取结构,但似乎有些错误。这是我的主要内容:

//Fraction structure
struct Fraction
{
int num, den;
};


int main()
{
int menu_selection;
char slash;

fstream datafile; //creates file object
Fraction* f; //creates pointer for dam

//menu to the user
menu_selection = main_menu();
bool condition = true;
while (condition)
{
    switch(menu_selection)
    {
    case 1: //adds a new Fraction structure to binary file
        f = new Fraction; //dynamically allocating memory
        cout << "Enter fraction to add: "; //adds fraction to file
        cin >> f->num >> slash >> f->den;//stores input
        datafile.open("fractions.dat",ios:: out | ios:: app | ios::binary); //creates file
        datafile.write(reinterpret_cast<char *>(f),sizeof(Fraction));//stores fraction to file
        datafile.close();
        menu_selection = main_menu();
        break;
    case 2:
        menu_selection = main_menu();
        break;
    case 3: //displays the contents of the file to user
        datafile.open("fractions.dat", ios::in | ios::binary);
        while(!datafile.eof())
        {
            datafile.read(reinterpret_cast<char *>(f),sizeof(f));
            cout << f->num << "/" << f->den << " ";
        }
        datafile.close();
        menu_selection = main_menu();
        break;
    case 4:
        menu_selection = main_menu();
        break;
    case 5:
        menu_selection = main_menu();
        break;
    case 6: condition = false;
        return 0;
        break;
    default: cout << endl << "That is an invalid option. Please try again." << endl; //default option
        break;
    }
}
delete f;
}

当用户输入1时,我为结构Fraction动态分配内存并将其写入二进制文件。我使用ios :: app因为我想再次调用它时添加到文件中。写作或阅读功能有什么问题吗?每当我按原样运行程序时,如果我输入一个分数(如1/5),它会显示1/5 5/5 5/5,但是如果我输入两个分数,如1/5和2/6,它会显示2/6 6/6 6/6。

1 个答案:

答案 0 :(得分:0)

    datafile.write(reinterpret_cast<char *>(f),sizeof(Fraction));//stores fraction to file

这没有任何意义。您必须将类实例转换为二进制格式才能存储它。你不能只告诉编译器假装你没有实际做到这一点!

文件是字节流。要将某些内容存储在文件中,您必须具有根据字节流(或块)指定的内容的格式。您不能只是欺骗编译器以完全未指定或任意格式将一些内存存储到磁盘。它可能包含指针!

这是另一个问题:

        datafile.read(reinterpret_cast<char *>(f),sizeof(f));

哎呀,f没有指向任何东西。所以你现在已经告诉编译器将数据读取到特定的位置。