I have an assignment where I need to read a certain number of Foos from a file. In case the data inside the file is ill-formed for one of the Foos, what are some common ways to signal (to stderr, for example) exactly which of the Foos should be corrected?
My code looks something like this:
Foo foos[50];
FILE *file = fopen(...);
int i;
for (i = 0; i < sizeof(foos); ++i)
{
if (readFoo(&foos[i], file) != 1)
break;
}
The readFoo function will return 1 if read is successful; if not, it will return a negative number and print an error to stderr which specifies what’s wrong but doesn’t say where the error is. How should I implement this (cleanely) so that I also tell the user the value of i?
In C++ I would do this with exceptions. In C I thought of doing something like this (readFoo would set error accordingly whenever something doesn’t go right):
/* These go in a source file */
const char *error = NULL;
const char error1[] = "Error 1 occurred.";
const char error2[] = "Error 2 occurred.";
const char *getLastError() {
return error;
}
What other ways are there to solve this?
The “clean” way to do this is to do the error reporting at the call site. That is, do something like:
if( readFoo( foos + i, file, errbuf, errbuf_size ) != 1 ) { fprintf( stderr, "%d: %s\n", i, errbuf ); ... }That is, have readFoo populate a buffer with the error message rather than writing it to stderr.