2010-09-11 29 views
1

我試圖寫入追加數據到文件末尾,並使用seekp(streamoff off,ios_base :: seekdir dir)函數,但它不會追加,它以某種方式寫入數據在文件中間。 我試着添加像這樣打開文件 - file.open(resultFile,fstream :: in | fstream :: out); (正如其他類似帖子中所建議的那樣),但我仍然得到相同的輸出。 即代碼:問題使用file.seekp

bool Manager::ValidCommand(Command* com, ofstream &ResultFile) const 
{ 
    Employee::DepartmentEn dept = Employee::InvalidDepartment; 
     if (com == NULL) 
      return false; 
     if(com->GetFunction() <Command::PrintCityCouncilList || com->GetFunction() > Command::HireEmployee){ 
      ResultFile.seekp(0,ios::end); 
      ResultFile << "Command:Failed activating function - invalid function number\n"; 
      return false;} 
     if ((com->GetFunction() == Command::PrintDepartmentEmployees) || (com->GetFunction() == Command::PrintDepartmentExpenses) || (com->GetFunction() == Command::PrintDepartmentStatistics)){ 
      dept = com->GetDepartment(); 
     if((pcc->FindDepartment(dept) == NULL)|| (dept < Employee::Engineering) ||(dept > Employee::Sanitation)) 
     { 
      ResultFile.seekp(0,ios::end); 
      ResultFile << "Command:Failed activating function - invalid department \n"; 
      return false; 
     } 
    } 
    return true; 
} 

我可能會做錯什麼?

+0

您是否嘗試明確設置二進制模式? failbit/badbit是什麼意思(請參閱http://www.cplusplus.com/reference/iostream/ostream/seekp/)? – AndiDog 2010-09-11 23:49:49

+0

你是否曾經寫過任何地方*但是*有問題的文件的結尾?如果所有的寫入操作都應該結束,那麼簡單的方法可能是用'std :: ios_base :: app'打開。 – 2010-09-11 23:57:03

+0

嘗試設置二進制模式,但沒有改變,並失敗函數返回false,所以我想沒有例外 – 2010-09-12 00:07:32

回答

0

什麼是變量 pcc在那裏做你的代碼引用?

if((pcc->FindDepartment(dept) == NULL) .....)) 
     { .... } 

因此對C++的文件輸入/輸出here這個文檔,並引述

OS ::應用中的所有輸出操作是在該文件的結束時進行,追加內容到當前文件的內容。此標誌只能用於打開輸出操作的流。

這意味着,如果同時指定了輸入/輸出模式,append將不起作用......您能證實這一點嗎?如果是這樣的話,可能值得忘記在文本模式下打開,並使用二進制模式,而不是...

另一件事 - 是文件絕對可以讓您尋找,ResultFile.seekp(...)?通過閃爍調試消息來檢查流的值,如下所示:

if (ResultFile.bad()) cout << "Bad stream!\n"; 
+0

它包含部門列表,它調用的功能是驗證某個部門是否存在 – 2010-09-12 00:12:02

+0

@Shiran:在這種情況下,這是一個全局變量嗎? – t0mm13b 2010-09-12 00:21:32

+0

它是一個全局變量(在主類中創建的更高類對象中的字段),並未在此函數中創建。 – 2010-09-12 00:26:43