2014-11-05 72 views
-1

我寫了一個小程序,打開一個文件,從文件的每一行建立一個矢量,然後讓用戶能夠從文件中添加/刪除。程序首先從矢量中刪除,然後根據矢量重建文件。下面是重建文件(文件名是文本文件的全名的成員變量,前碼「的test.txt」:寫入文件結果爲空文件

bool rebuildFile() { 
    if (remove(fileName.c_str()) == 0) { // remove the old file 
     ofstream newFile(fileName);   // create new file with same name 
     newFile.open(fileName, ios::app); // open to append to end of file 
     if (newFile.is_open()) {    
      newFile << fileHeader << endl; // add the first header line 
      for (int i = 0; i < myVector.size(); i++) { // loop through vector, adding strings to file 
       newFile << myVector[i] << endl; // I used "\n" instead of endl, but both give same results 
      } 
      newFile.close(); 
      return true;  // success 
     } 
    } 
    return false;   // failure 
} 

這個函數退出後,該文件是完全空的,所以它。清楚地創建了一個新文件,但寫作部分是一個問題,我不知道爲什麼。我閱讀其他文章,其中有一些問題,他們有文件在Notepad/Notepad ++中打開,但我一直確定在運行程序之前關閉該特定文件我不確定ios :: app標誌是否導致循環問題,但文檔似乎很清楚,它只是指向每次輸出到文件結尾它,所以我不認爲問題在那裏。任何想法?

編輯:

顯然你不能附加到一個空文件...這個新的代碼工作,但我不知道是否有一個「更乾淨」的方式添加到文件以兩種不同的方式,而無需打開和用不同的標誌關閉兩次。

新代碼:

bool rebuildFile() { 
    if (remove(fileName.c_str()) == 0) { 
     std::ofstream newFile(fileName); 
     newFile.open(fileName); 
     if (newFile.is_open()) { 
      newFile << fileHeader << endl; 
      newFile.close(); 
     } 
     newFile.open(fileName, std::ofstream::out | std::ofstream::app); 
     if (newFile.is_open()) { 
      for (int i = 0; i < myVector.size(); i++) { 
       newFile << myVector[i] << endl; 
      } 
      newFile.close(); 
      return true; 
     } 
    } 
    return false; 
} 
+1

所以你刪除舊文件,創建一個新的文件,然後附加到那個文件裏面什麼都沒有? O.o我不明白。 – deW1 2014-11-05 12:16:53

+0

我不認爲這會是一個問題......我想我仍然可以附加到該文件,只是最後也將是文件的開始。 – floatfil 2014-11-05 12:18:55

+0

謝謝deW1,這是問題! – floatfil 2014-11-05 12:29:28

回答

3

試圖調用open在已打開的文件流將流處於故障狀態。

只要改變

ofstream newFile(fileName);   // create new file with same name 
    newFile.open(fileName, ios::app); 

ofstream newFile(fileName, ios::app); 

[ofstream.members]

void open(const char* s, ios_base::openmode mode = ios_base::out);

影響:致電rdbuf()->open(s, mode | ios_base::out)。如果 功能確實不會返回一個空指針調用clear()否則調用 setstate(failbit)(這可能會引發ios_base::failure(27.5.5.4))。

[音響lebuf.members]

basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);

ÊFF學分:如果is_open() != false返回空指針。 [...]

bool is_open() const;

返回:真要是到open以前調用成功(返回 非空值),並出現了中間沒有調用close

0
ofstream newFile(fileName); 

不只是創建文件,它會打開它。這意味着你不能再打開它。

我沒有看到一個理由刪除文件,重新創建它 - 如果它存在截斷 - 打開它,寫一點,關閉文件,打開它再次但對於追加,然後寫更多。

另外,如果你運氣不好,有一個不同的過程修改(或刪除)第一個close和第二個open之間的文件的機會,這通常不是一件好事。

這段代碼應該工作:

bool rebuildFile() 
{ 
    std::ofstream newFile(fileName); 
    if (newFile) 
    { 
     newFile << fileHeader << endl; 
     for (int i = 0; i < myVector.size(); i++) { 
     newFile << myVector[i] << endl; 
     } 
    } 
    return newFile; 
} 

(文件將被自動關閉,如果需要的話,通過ofstream的析構函數。)