I am writing a program with a class that has an fstream member. The functions for the class is to open a file, read and print the last line of a file, and close a file. The functions work for the first file but not when I open a second or third file - it does not matter what file I use it is always the second one that has the error. This program works fine on Linux but not on Windows. I have tried opening the files in binary and the same problem still occurs.
After I open the second file, I go through my get(char) function once, and my tellg() randomly moves from 17 to -1 instead of from 17 to 18. Can anyone help me figure out why this is?
void Files::getLastLine(){
bool searchForStartLine = true;
char location;
//If its open
if(accountFile.is_open()){
//Go back one space
accountFile.seekg(-1, ios::cur);
//While I want to search for the start of a line
while (searchForStartLine == true){
//Get the character of tellg
accountFile.get(location);
//If tellg is <=1 then its at the start so stop looking
if (accountFile.tellg() <= 1){
//set seekg to start
accountFile.seekg(0);
//stop looking
searchForStartLine = false;
}
//see if its at a new line
elseif (location == '\n'){
//if it is then stop
searchForStartLine = false;
}
//if its not at the start or new line
else{
//move back to start of char and then back one more to get the next char
accountFile.seekg(-2,ios::cur);
}
}
//get the line of the file
getline(accountFile, strLastLine);
cout << strLastLine << "\n";
}
}
I have checked and the first file does work completely and the last line gets printed. It also closes completely. The second file also opens completely but has its tellg() reset after the get(char) function.
I go through my get(char) function once, and my tellg() randomly moves from 17 to -1
tellg() doesn't "move to -1". It fails, and returns -1 to indicate that it failed. It can fail for several reasons, one of which is that the stream already has the failbit set. Start by checking if each of your I/O operations (get(), getline(), seekg(), tellg()) fail (for debugging purposes, you could print accountFile.fail() after each operation)
(and yes, relative seeks aren't expected to work on files opened in text mode)
So I found out that the get() function was failing for the second file, and adding a blank line at the end of the text files makes the program work, but I do not know why.
so if the files look like this
file1:
"text"
"Blank line" EOF.
then it works.
but if the files look like this
file1:
"text" EOF.
it doesn't work.