读二进制返回垃圾

时间:2012-12-13 00:04:07

标签: c++

我正在编写一个函数来保存链表并将其作为二进制文件加载。当我尝试加载它停止的功能时;该程序不会崩溃或冻结,但不会超出指示点:

 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;
}

N也不是很大;我已经检查了

1 个答案:

答案 0 :(得分: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;
}