2012-12-13 95 views
1

我正在寫一個函數來保存和加載鏈接列表作爲二進制文件。當我嘗試加載停止的函數時,該程序不會崩潰或凍結,但它不會繼續超出指示的點:讀取二進制返回垃圾

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也是可笑的大;我查過

+8

目前還不清楚你的代碼是否被讀取或寫入 - 你打開'的fstream :: in'模式,但調用'fin.write()'。這是你的意圖嗎? –

回答

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