Using errno

Lots of functions in the C standard library will set errno to an error code if something goes wrong, so using errno in your programming can help you pinpoint where problems are occurring and what they might be.

errno remains set at the last error code, so bear in mind that:

a) if two subsequent functions are returning errors, you’ll miss the first one if you’re not looking for it, and

b) a function called after one that returns an error does not set errno back to zero (but you can set errno to zero if you like).

How do I use errno?

First of all, include the header in your C program:

#include <errno.h>

Or in your C++ program:

#include <cerrno>

Then, you can access the error code just by using the integer errno.

OK, I’ve got a number from errno, but what does it mean?

All the error codes are defined in the errno.h header file. On Linux this lives somewhere like:

/usr/include/linux/errno.h

Er, isn’t there an easier way to see what’s going wrong?

Well there is, since you ask. You can use strerror to return the actual text error message.

See the example code, and its output below – this will return a nice error message and save you having to rummage through the file looking for an error to match the code you’ve been given. Handy, eh?

Output

Attempting file access...
Something went wrong! errno 13: Permission denied

Source

#include <iostream>
#include <cerrno>
#include <string.h>
#include <stdio.h>
int main()
{
    std::cout << "Attempting file access..." << std::endl;
    FILE *f = fopen("/proc/cpuinfo","w");
    if (f == NULL)   
    {       
        std::cout << "Something went wrong! errno " << errno << ": ";
        std::cout << strerror(errno) << std::endl;
    }
    return 0;
}