[英]Unable to read new line of a file
我對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,因為我正在嘗試將位置重置為文件的開頭。 我對此有什么想念的地方或誤解嗎? 如果我關閉然后重新打開文件,那很好,但是我很好奇是否存在一種無需關閉就可以繼續讀取文件的方法。 謝謝您的幫助 :)
您沒有清除流的狀態,因此seekg
調用沒有執行任何操作。 您需要在重新定位之前添加myFilein.clear()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.