Skip to content
how to use errno in c and c++

Check out my free resources and deep-dive courses.

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:

1. If two subsequent functions return errors, you’ll miss the first one if you’re not looking for it.
2. errno should only be checked when a function reports an error, as a successful function call doesn’t reset its value to zero. Always check the function’s return value first, then inspect errno to find out what went wrong (but you can set errno to zero at any time, 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 yes 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?

Example Output

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

Example Source Code

#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;
}

free the mallocs mug gift

A little something I made

When I’m not writing about code, I design geeky mugs. If you’d like one for your desk, or know someone who would, take a look at my designs.

1 thought on “How to Use errno in C and C++”

  1. Gods, I just found out about your site.
    gnu/linux user, gdb, bash, etc. are you a godess?

    You must be one of the coolest mothers alive on earth
    today.

    All the best.

    /fanboyrant

Leave a Reply

Your email address will not be published. Required fields are marked *

Save to list