Search code examples
cposixerrno

"File corrupt" errno?


Is there a conventional errno code to indicate that the specified file is corrupt (it does not conform to the file format it should be)?

I am writing a file parser and don't know what the most appropriate code to return is. There's always EINVAL, though I was hoping for something more specific than that, since that would be used for any other invalid parameter as well, and especially in my case it's of value for the caller to know that the call failed because the file was corrupt.

EBADF, EDOM, EILSEQ, EIO, ENOSTR, EPROTO are the ones I saw that could by some stretch of the imagination be used for such a meaning, but is there a convention for this case?


Solution

  • Well, POSIX (and UNIX before it) imposes no format for a file, so it's difficult to signal a failure in format. A file is simply a sequence of bytes, where any byte can follow to the previous one in the file. No record boundaries or sizes have to be specified on reading, so How can we identify tha a file is not format conformant?

    Errno values are for identifying system errors (errors produced as a consequence of some condition in the system when issuing a system call) so no ESOMETHING constant for bad format.

    By the way, the list of numbers that conform the values for the errno variable is system specific, and is subject to change from version to version of kernel/stdlib... so you cannot select a number and be sure that the number you selected will not be used by the system in a future version.

    For this reason, it is bad practice to use errno to return error codes. Many libraries follow the same pattern as stdlib, but with a prefixed something_errno variable. This is my recomendation for you.

    Anyway, a parser normally returns return a parse tree (syntactic tree) and you can use node fields to indicate parsing errors anyway. Don't pollute the meanings of the system errors using them for nothing but what they were designed for.