2012-04-27 44 views
1

我有一個任務,我正在寫輸入的各種東西(以結構的形式),然後寫入二進制文件。在程序打開時,我必須能夠讀取和寫入文件。其中一種方法需要打印出二進制文件中的所有客戶端。它似乎在工作,除非每次我調用該方法時,它似乎都會擦除文件的內容,並防止將其寫入更多內容。這裏是適用的片段:C++二進制文件方法是從文件中刪除內容?

fstream binaryFile; 
binaryFile.open("HomeBuyer", ios::in | ios::app | ios::binary); 

同樣的文件應該是運行程序時間之間可用的,所以我應該與iOS應用::打開它,對嗎?

下面就來添加一個條目的方法:

void addClient(fstream &binaryFile) { 
     HomeBuyer newClient; //Struct the data is stored in 
     // -- Snip -- Just some input statements to get the client details // 

     binaryFile.seekp(0L, ios::end); //This should sent the write position to the 
            //end of the file, correct? 
     binaryFile.write(reinterpret_cast<char *>(&newClient), sizeof(newClient)); 

     cout << "The records have been saved." << endl << endl; 
} 

而且現在的方法來打印所有條目:

void displayAllClients(fstream &binaryFile) { 
    HomeBuyer printAll; 
    binaryFile.seekg(0L, ios::beg); 
    binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll)); 

    while(!binaryFile.eof()) { //Print all the entries while not at end of file 
     if(!printAll.deleted) { 
      // -- Snip -- Just some code to output, this works fine // 
     } 

     //Read the next entry 
     binaryFile.read(reinterpret_cast<char *>(&printAll),sizeof(printAll)); 
    } 
    cout << "That's all of them!" << endl << endl; 
} 

如果我通過程序步驟,我可以輸入儘可能多的客戶作爲我想,並且它會在我第一次調用displayAllClients()時輸出它們。但是一旦我調用displayAllClients()一次,它似乎就清除了二進制文件,並且任何進一步的顯示客戶端的嘗試都不會給我帶來任何結果。

我是否正確使用seekp和seekg?

據我所知,這應該設置我的位置寫在文件的結尾:

binaryFile.seekp(0L, ios::end); 

這應爲我設置讀取位置的開頭:

binaryFile.seekg(0L, ios::beg); 

謝謝!

+0

檢查寫入是否成功,我不確定'ios :: out'是否在'ios :: app'時隱式指定。 – hmjd 2012-04-27 21:36:21

+0

寫道似乎是成功的,但我嘗試了與ios :: out只是爲了檢查,它似乎是做同樣的事情。也就是說,直到我調用除addClient()方法之外的方法之前,寫入似乎都成功了。 – Nate 2012-04-27 21:40:00

+2

我想你還需要在seekf()和seekg()之前調用''binaryFile.clear()''如果EOF被設置,否則它們將不起作用。 – hmjd 2012-04-27 21:41:05

回答

3

粘貼評論,因爲這解決了這個問題。

你需要seekp()seekg()如果EOF設置之前調用binaryFile.clear(),否則他們將無法正常工作。

+0

謝謝,這似乎已經做到了。我在其他地方仍然存在問題,但我認爲這可能與窒息答案有關。謝謝! – Nate 2012-04-27 21:50:19

1

這是IOS文件::應用

ios::app 

    All output operations are performed at the end of the file, appending the 
    content to the current content of the file. This flag can only be used in 
    streams open for output-only operations. 

由於這是家庭作業,我會讓你得出自己的結論。

+0

這將是有道理的,謝謝。 – Nate 2012-04-27 21:51:01