2013-12-16 35 views
0

我對C++編程頗爲陌生,而且在從已打開的文件中讀取時遇到問題。我正在做的是寫入一個文件,從中讀取數據,並添加到文件末尾,然後再次嘗試讀取它,而不必關閉原始的ifstream。代碼如下:無法讀取文件的新行

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

using namespace std; 

int main() 
{ 
    ofstream myFile ("example.dat"); 

    // Open and write to file 
    if (myFile.is_open()) 
    { 
     myFile << "This is a line." << endl; 
     myFile << "This is another line." << endl; 
     myFile.close(); 
    } 
    else cout << "no"; 

    // Open and read from file 
    string line; 
    ifstream myFilein ("example.dat"); 
    if (myFilein.is_open()) 
    { 
     while (getline(myFilein,line)) 
     { 
      cout << line << myFilein.tellg() << endl; 
     } 
     //myFilein.close(); 
    } 

    // Open and add to end of file 
    if (!myFile.is_open()) 
    { 
     myFile.open("example.dat", ios::app); 
     myFile << "This is the last line." << endl; 
     myFile.close(); 
    } 

    //myFilein.open("example.dat", ios::ate); 

    // Read from already open file 
    myFilein.seekg(0, ios::beg); 
    if (myFilein.is_open()) 
    { 
     cout << "myFilein is open. " << myFilein.tellg() << endl; 
     while (!myFilein.eof()) 
     { 
      getline(myFilein, line); 
      cout << line << endl; 
     } 
    } 
    myFilein.close(); 

    int holdClose; 
    cin >> holdClose; 

    return 0; 
} 

顯然,事情錯了,因爲所以tellg()的初始讀取後,返回值-1(即,它遇到文件結束後),但我我不完全確定它爲什麼會返回-1,因爲我試圖將位置重置爲文件的開頭。有什麼我失蹤或誤解這是如何工作的?如果我關閉並重新打開文件,那就沒有問題,但我很好奇,如果有方法可以繼續閱讀而不必關閉它,如果這是有道理的。感謝您的幫助:)

+4

一旦文件上有錯誤標誌,比如'eof',如果你想繼續使用文件,你需要使用'myFilein.clear()'來重置它們。 –

+0

就是這樣!謝謝,@RetiredNinja! –

回答

0

您沒有清除流的狀態,因此seekg調用什麼都沒做。您需要在重新定位之前添加myFilein.clear()