2016-03-06 68 views
-3

編輯:改變我的問題,以更準確的情況編輯:麻煩檢查文件是否爲空,我做錯了什麼?

我想打開一個文本文件(創建它,如果它不存在,打開它,如果沒有)。它與輸出是相同的輸入文件。

ofstream oFile("goalsFile.txt"); 
fstream iFile("goalsFile.txt"); 
string goalsText; 
string tempBuffer; 
//int fileLength = 0; 
bool empty = false; 

if (oFile.is_open()) 
{ 
    if (iFile.is_open()) 
    { 
     iFile >> tempBuffer; 
     iFile.seekg(0, iFile.end); 
     size_t fileLength = iFile.tellg(); 
     iFile.seekg(0, iFile.beg); 
     if (fileLength == 0) 
     { 
      cout << "Set a new goal\n" << "Goal Name:"; //if I end debugging her the file ends up being empty 
      getline(cin, goalSet); 
      oFile << goalSet; 
      oFile << ";"; 
      cout << endl; 

      cout << "Goal Cost:"; 
      getline(cin, tempBuffer); 
      goalCost = stoi(tempBuffer); 
      oFile << goalCost; 
      cout << endl; 
     } 
    } 
} 

幾個問題。首先,如果文件存在並且文件內有文本,它仍會進入if循環,通常會要求我設置一個新目標。我似乎無法弄清楚這裏發生了什麼。

+0

嘆息.. 爲什麼downvotes? – Robolisk

+0

尋求到最後,並獲得位置。如果它是零,那麼文件是空的。 –

+0

是的,但爲什麼我沒有工作,爲什麼發生了什麼,發生了什麼? – Robolisk

回答

1

問題在於您使用的是緩衝IO流。儘管它們在下面引用了相同的文件,但它們有完全獨立的緩衝區。

// open the file for writing and erase existing contents. 
std::ostream out(filename); 
// open the now empty file for reading. 
std::istream in(filename); 
// write to out's buffer 
out << "hello"; 

在這一點上,「你好」可能沒有被寫入磁盤,唯一的保證是,它是在out輸出緩衝區。迫使它被寫入到磁盤,您可以使用

out << std::endl; // new line + flush 
out << std::flush; // just a flush 

這意味着,我們致力於我們的輸出到磁盤,但輸入緩衝器仍然不變,在這一點上,所以文件仍然顯示爲空。

爲了讓您的輸入文件看到您寫入輸出文件的內容,您需要使用sync

#include <iostream> 
#include <fstream> 
#include <string> 

static const char* filename = "testfile.txt"; 

int main() 
{ 
    std::string hello; 

    { 
     std::ofstream out(filename); 
     std::ifstream in(filename); 
     out << "hello\n"; 
     in >> hello; 
     std::cout << "unsync'd read got '" << hello << "'\n"; 
    } 

    { 
     std::ofstream out(filename); 
     std::ifstream in(filename); 
     out << "hello\n"; 

     out << std::flush; 
     in.sync(); 

     in >> hello; 
     std::cout << "sync'd read got '" << hello << "'\n"; 
    } 
} 

你會碰到試圖與緩衝流做到這一點,接下來的問題是需要clear()每個更多的數據被寫入到文件時,輸入流中的EOF位...

+0

關於這個和我的代碼,然後不嘗試閱讀的內容,只是檢查它是否是空的它將永遠是空的?考慮到我想檢查它是否已經有內容,那麼就決定如何處理它(在這種情況下,從用戶那裏得到目標)。 通過使用同步,然後做檢查,你建議這可能是我的解決方案? 我不知道如何使用符合我的代碼情況的「同步」。 – Robolisk

+0

您發佈的代碼首先打開文件以非追加模式寫入,這實際上使文件變空。如果您想知道文件是否爲空,請在打開文件之前對其進行測試。 1 /測試是否可以打開它,即文件是否存在; 2 /測試你是否在沒有閱讀的情況下,如果是,那麼文件是空的。 – kfsone

+0

OMG APPEND MODE。這是所有問題的全部問題,謝謝你,我是如何忽略這一點的。不過謝謝你的同步想法,這是我從未考慮過的一件非常乾淨的事情 – Robolisk

1

嘗試Boost::FileSystem::is_empty它測試您的文件是否爲空。我讀過使用fstream的地方不是測試空文件的好方法。

+0

我不確定這是什麼:/ – Robolisk

+0

@Robolisk是一個可移植的庫,具有良好的模板和功能來執行平臺獨立任務,例如存在文件,空文件,文件大小等,有很多示例在網上關於如何使用它們,像這[一個](http://theboostcpplibraries.com/boost.filesystem-files-and-directories),它顯示了一些帶有文件的庫的例子。 – Joel