C - Errors - Handling errors

In this tutorial we will how to easily manage errors in C programming language.

That is we will try to open a file and if this file doesn't exist we will trigger an error.
If the file exists, we will tell its name with a message to say that the file really exist.

We have to notice that for handling errors correctly, we have to use the fprintf() function to indeed display error on the error output.
For the standard output, we will use the classical printf() function.

Now, the code:


 * main.c



#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

#include <string.h>

#include <errno.h>

int main (int ac, char *av[])


int fd;

fd = open(av[1], O_RDONLY);

if (fd == -1)


   fprintf(stderr, "Error: '%s'. %s\n", av[1], strerror(errno));

   return 1;




printf("The file you are trying to open is '%s' and exists!\n", av[1]);


close (fd);

return 0;

Now, try to open a file that exist, and one that doesn't exist to see the difference. laugh

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.