In a situation where a text file is read line by line through a while
loop, what is the recommended method for dealing with errors?
(note: fggets
from here is used)
bool SomeClass::ReadFile(int ignorelines) {
FILE *file = fopen(m_filepath.c_str(), "r");
if (file!=NULL) {
char *buffer; //line reading buffer
while (fggets(&buffer,file)==0) { //read line (fggets returns non-zero at provided terminator or \eof)
if (ignorelines>0) {
ignorelines--; //count the lines ignored
free(buffer);
continue;
}
line.assign(buffer);
if (!PerformLineCheck1(buffer)) {
m_error+="The line is not allowed.\n";
free(buffer);
fclose(file);
return false;
}
if (!PerformLineModification1(buffer)) {
m_error+="The line could not be modified properly.\n";
free(buffer);
fclose(file);
return false;
}
if (!PerformLineExtraction(buffer)) {
m_error+="The variables could not be extracted.\n";
free(buffer);
fclose(file);
return false;
}
//extracted all, now continue with next line
free(buffer); //clear up the line
}
fclose(file);
return true;
}
m_error+="There was an error opening the data file.\n";
return false;
}
There are some options I could think of:
- use
break;
to get out of thewhile
loop: but then I would need to addfree(buffer);
which can cause freeing memory twice. - use
try
andcatch
, however this deals with all other exceptions in those functions as well and suggested was to use assert (as suggested here). However, assert will assume code errors and break operation, while for this situation program execution can continue, the function simply needs to return false.
What is the suggestion for something like the loop above?