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.
Please help.
String activeFile = "/var/tmp/active.txt";
String tempFile = "/var/tmp/temp.txt";
ifstream file_active;
file_active.open(activeFile);
char oneLine[255];
if (file_active.is_open())
{
cout << "File open successful" << endl;
ofstream temp_active(tempFile);
while (!file_active.eof())
{
memset (oneLine, '\0', sizeof(oneLine));
file_active.getline(oneLine, 255);
if (oneLine.is_empty())
{
continue;
}
temp_active << oneLine << endl;
}
file_active.close();
temp_active.close();
}
else
{
cout << "Error opening file" << endl;
}
//Remove the original file i.e. activeFile
int status = removeFile(activeFile);
if (status)
{
//Rename temp file to original file
renameFile(tempFile, activeFile);
}
cout << "The contents of the file finally are: "char finalLine[255];
file_active.open(activeFile);
//The code is not printing the contents of this file
//Gets struck inside the loop printing empty lines.
if (file_active.is_open())
{
while(!file_active.eof()) // To get you all the lines.
{
memset(finalLine, '\0', sizeof(finalLine));
file_active.getline(finalLine,255);
cout << finalLine << endl;
}
}
But the same code works fine sometimes. And sometimes it gets struck, though it's not very clear to me when it gets struck.
Will you please elaborate on why it's going to infinite loop?
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