2012-12-11 21 views
0

我正在嘗試編寫一個程序來保存鏈接列表的內容(每個單獨的列表稱爲一個地方幷包含數據類型的混合)。代碼編譯但意外終止;它指向我ifstream庫中的行(儘管我只想使用寫入)爲fstream添加NULL終止符

*_Str = _Elem(); // add terminating null character 

有沒有人有一個想法什麼是錯誤?

//saves a single locality onto a file 
    void fSave_locality(Clinked *current, fstream *fout) 
    { 
     fout->write(current->site_name,100); 
     fout->write((char*) &current->cood_x,sizeof(double)); 
     fout->write((char*) &current->cood_y,sizeof(double)); 
     fout->write((char *) &current->dip,sizeof(double)); 
     fout->write((char *) &current->strike,sizeof(double)); 

     if (current->next!=NULL) fSave_locality(current->next,fout); 
    } 

    void fSave_list(char* fname) 
    { 
     fstream *fout; 
     do 
     { 
      cout<<"Would you like to save as a (b)inary or (t)ext file? "; 
      test = getch(); 
      cout<<"Enter file name (make sure its unique!): "; 
      cin.getline(fname,100); 

      if(toupper(test)=='T') fout->open(fname, fstream::out); 
      if(toupper(test)=='B') fout->open(fname, fstream::out| fstream::binary); 
     } 
     while(toupper(test)!='T' || toupper(test)!='B'); 

     if(fout->fail()) 
     { 
      cout<<"unable to open file.\n"; 
      exit(0); 
     } //it gets to here without any problems. 

     current = start; 
     while(current->next!=NULL) 
      { 
       fSave_locality(current, fout); 
       current=current->next; //repeat for the next object in the list 
      } 
     fout->close(); 
    } 
+0

你使用調試器來確定哪些錯誤發生的具體行? (如果你使用'gdb',你應該使用'b(ack)t(race)') – Zeta

+1

fname設置爲什麼?我猜這可能是罪魁禍首。在另一個說明中,你確定最後一個循環不應該是「while(current!= NULL)」嗎? – DrC

+0

如果回答這個問題,我正在使用Visual Studios 2010? (抱歉,如果沒有;計算不是我的強項) –

回答

0

我不明白你爲什麼在同一時間遞歸迭代迭代? 只需選擇其中一個,我更改了代碼,還需要爲while循環設置正確的限制,並確保不使用空對象並嘗試訪問空對象上的元素。

void fSave_locality(Clinked *current, fstream *fout) 
    { 
     fout->write(current->site_name,100); 
     fout->write((char*) &current->cood_x,sizeof(double)); 
     fout->write((char*) &current->cood_y,sizeof(double)); 
     fout->write((char *) &current->dip,sizeof(double)); 
     fout->write((char *) &current->strike,sizeof(double)); 

     //if (current->next!=NULL) fSave_locality(current->next,fout); // comment this out 
    } 

,並更改以下部分:

while(current!=NULL) 
    { 
     fSave_locality(current, fout); // you should either comment this one or the recursive one 
     current=current->next; //repeat for the next object in the list 
    } 
+0

我沒有看到它導致報告的問題,但絕對是一個好點。 – DrC

+0

您應該提供更多細節,堆棧跟蹤或異常詳細信息 –

+0

我按照您的說法做了,並且我也意識到'cin name'部分應該出現在main函數中,然後將其用作fSave_list的參數。 –