1

I'm writing a function to save and load a linked list as a binary. When I try to load the function it stops; the program doesn't crash or freeze but it won't continue beyond the point indicated:

 void fLoad(char* fname)
{
    fstream fin;
    fin.open(fname, fstream::in|fstream::binary);

    if(fin.fail())
        {
            cerr<<"unable to open file";
            exit(0);
        }
    cout<<"File open";

    fin.read((char*) &N, sizeof(int));
    cout<<N;
    system("pause");
    for(int i=0;i<N;i++)
    {
        Clinked* current = new Clinked;

        fin.write(current->site_name,sizeof(char)*100);
        fin.write((char*) &current->cood_x,sizeof(double));
        fin.write((char*) &current->cood_y,sizeof(double)); 
        fin.write((char*) &current->dip,sizeof(double)); 
        fin.write((char*) &current->strike,sizeof(double)); 

        //fin.write((char*) current, sizeof(Clinked));

        current->next=start;
        start=current;
    } //at this point it stops

    cout<<"\n"<<fname<<" was read succesfully";
    fin.close();
    cout<<endl;
}

It's not that N is ridiculously large either; I've checked

4

1 回答 1

1

正如评论中所指出的,您正在使用write而不是read. 您的代码可能会引发异常,请在引发异常时在Debug > Exceptions菜单中检查Break

我认为您的代码应如下所示:

void fLoad(char* fname)
{
    fstream fin;
    fin.open(fname, fstream::in|fstream::binary);

    if(fin.fail())
    {
        cerr<<"unable to open file";
        exit(0);
    }
    cout<<"File open";

    fin.read((char*) &N, sizeof(int));
    cout<<N;
    system("pause");
    for(int i=0;i<N;i++)
    {
        Clinked* current = new Clinked;

        fin.read(current->site_name,sizeof(char)*100);
        fin.read((char*) &current->cood_x,sizeof(double));
        fin.read((char*) &current->cood_y,sizeof(double)); 
        fin.read((char*) &current->dip,sizeof(double)); 
        fin.read((char*) &current->strike,sizeof(double)); 

        //fin.read((char*) current, sizeof(Clinked));

        current->next=start;
        start=current;
    } //at this point it stops

    cout<<"\n"<<fname<<" was read succesfully";
    fin.close();
    cout<<endl;
}
于 2012-12-13T02:11:40.140 回答