Is there anything wrong with the following piece of code?
I have one original file at some location. I copy it's contents excluding the blank lines to some temp file in the same location. Then I delete the original file and rename the temp file with the name of the original file. And at last print the contents of the renamed file.
The problem is my code gets struck while printing the final contents of the file. It doesn't come out of the loop. Just keeps printing empty lines.
String activeFile = "/var/tmp/active.txt";
String tempFile = "/var/tmp/temp.txt";
cout << "File open successful" << endl;
memset (oneLine, '\0', sizeof(oneLine));
temp_active << oneLine << endl;
cout << "Error opening file" << endl;
//Remove the original file i.e. activeFile
int status = removeFile(activeFile);
//Rename temp file to original file
cout << "The contents of the file finally are: "char finalLine;
//The code is not printing the contents of this file
//Gets struck inside the loop printing empty lines.
while(!file_active.eof()) // To get you all the lines.
memset(finalLine, '\0', sizeof(finalLine));
cout << finalLine << endl;
Will you please elaborate on why it's going to infinite loop?
The infinite loop happens when the stream has its badbit or failbit flags on (the flags are never checked and never cleared). The array version of getline() that's called here sets the failbit when it extracts the specified number of characters minus one (254) without encountering the end of line.
(btw, memset() is completely unnecessary: even when reading past the end of file, which is what this loop does when it doesn't go infinite, istream::getline() writes a null character to the first position of the array)
The book "The c++ standard library", on page 519, said : "Note that you always have to clear error bits explicitly. In C it was possible to read characters after a format error. For example, if scanf() failed to read an integer, you could still read the remaining characters. Thus, the read peration failed, but the input stream was still in a good state. This is different in C++. If failbit is set, each following stream operation is a no-op until failbit is cleared explicitly"
so, you shoud call file_active.clear to clear the previous eof error bit before the second call to file_active.open