I've been trying to find a way to stop an infinite Getline() loop from reading the last line in a file.
I'm hoping to be able to pause a parsing program when it reaches the last line so the stream doesn't get closed. I then want it to resume when a new line has been added to the log file.
I've written this code here and it seems to do half of what I want it to do. But i'm not sure why the filestream is closing. It can detect when it reaches the end of the file and it won't enter the IF bracket once the end is reached.
However when I add new data to the text file it doesn't read the line any more.
I tried to simplify down the code a bit to make it easier to see the problem.
I am using -1 here if (fin.peek() != -1){; because that's what std::cout << fin.peek() << "\n"; is returning after the last line is read.
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
constint MAX_CHARS_PER_LINE = 512;
constint MAX_TOKENS_PER_LINE = 128;
int main()
{
std::ifstream fin; // create a file-reading object
fin.open("testfile.txt"); // open the file
if (!fin.good())
return 1; // exit if file not found
while (true)
{
std::cout << fin.peek() << "\n";
//Only take these actions if there is another line in the file stream
if (fin.peek() != -1){
std::cout << fin.peek() << "\n";
// read an entire line into memory
char buf[MAX_CHARS_PER_LINE];
fin.getline(buf, MAX_CHARS_PER_LINE);
}//If Bracket
std::cout << "Press Any Key To Loop Again\n";
getch();
}//Infinite Loop Bracket
}//Main Function Bracket
I'm hoping to be able to pause a parsing program when it reaches the last line so the stream doesn't get closed.
Well, the stream doesn't actually close until either an explicit call to close() or the fstream object's destructor is called. However the fail() and eof() flags may be set. Use clear() to unset the flags and allow further use of the stream.
I may have misunderstood your requirements, but this may work. Press the escape key to quit.