13.17. perror()

Print the last error message to stderr


#include <stdio.h>
#include <errno.h>  // only if you want to directly use the "errno" var

void perror(const char *s);


Many functions, when they encounter an error condition for whatever reason, will set a global variable called errno for you. errno is just an interger representing a unique error.

But to you, the user, some number isn't generally very useful. For this reason, you can call perror() after an error occurs to print what error has actually happened in a nice human-readable string.

And to help you along, you can pass a parameter, s, that will be prepended to the error string for you.

One more clever trick you can do is check the value of the errno (you have to include errno.h to see it) for specific errors and have your code do different things. Perhaps you want to ignore certain errors but not others, for instance.

The catch is that different systems define different values for errno, so it's not very portable. The standard only defines a few math-related values, and not others. You'll have to check your local man-pages for what works on your system.

Return Value

Returns nothing at all! Sorry!


fseek() returns -1 on error, and sets errno, so let's use it. Seeking on stdin makes no sense, so it should generate an error:

#include <stdio.h>
#include <errno.h> // must include this to see "errno" in this example

int main(void)
    if (fseek(stdin, 10L, SEEK_SET) < 0)

    fclose(stdin); // stop using this stream

    if (fseek(stdin, 20L, SEEK_CUR) < 0) {

        // specifically check errno to see what kind of
        // error happened...this works on Linux, but your
        // mileage may vary on other systems!

        if (errno == EBADF) {
            perror("fseek again, EBADF");
        } else {
            perror("fseek again");

    return 0;

And the output is:

fseek: Illegal seek
fseek again, EBADF: Bad file descriptor

See Also

feof(), ferror(), clearerr()