Mahmoud Mubarak Mahmoud Mubarak - 1 month ago 8
C Question

fread and ferror don't set errno

I'm trying to check when

fread()
raises an error, so I use
ferror()
.

chunk = fread(buf, 1, 100, file);
if (ferror(file))
{
return errno;
}


But,
ferror()
man page says:


ERRORS These functions should not fail and do not set the external variable errno.


So, how can I know the error type occurred when file has been read, although
fread()
and
ferror()
didn't set
errno
?

Answer

You can't get there from here.

fread does not set errno (as you have discovered), and as such you cannot really determine much about a specific error state; only that there is one. The exact nature of the error is generally implementation-dependent. There is no C standard-library-based portable way to gather it .

For specific system-level errors, you can slum it to system-calls, possibly suffering with the pitfalls like poor/nonexistent IO buffering along the way. There POSIX can somewhat come to your rescue. Calls like read, do set errno and have a fairly detailed set of possible outcomes. That may be an option for you if the platform you're working with is POSIX compliant and the code is really so critical to be in-the-know.

But from the C standard library, you're not going to find much beyond being told an error has happened. Generally you'll find you don't need more than that anyway.

Comments