errno vs perror

(1) What is the difference between errno and perror? Why use one over the
other? Why use both of them together?

(2) What is the point in the else statement in the following function, if
either way an error message is spit out?

1
2
3
4
5
6
7
8
9
10
11
void die(const char *message)
  {
      if(errno) {
          perror(message);
      } else {
          printf("ERROR: %s\n", message);
      }
  
      exit(1);
  }
  
Well...

errno
http://www.cplusplus.com/reference/cerrno/errno/

perror
http://www.cplusplus.com/reference/cstdio/perror/

errno starts off as zero, so the code looks like it's intended to display some sort of default message if errno hasn't been set.

But it displays the error message corresponding to errno if it has been set.

Andy
errno is part of a traditional error handling system.
Certain functions, when they fail, will set up errno to a certain value, different from zero.
Then you use perror() to print the "human readable" error message associated with errno's value, and you can add your own custom message too.
http://www.cs.cf.ac.uk/Dave/C/node18.html#SECTION001810000000000000000

(2) What is the point in the else statement in the following function, if
either way an error message is spit out?

To be pedantic, the else branch should print to stderr instead of stdout, to say that it prints an error message.
fprintf(stderr, "ERROR: %s\n", message);

Anyway, my post is just an educational supplement to Andy's. He answered your questions well.

Edit: incoherency.
Last edited on
Topic archived. No new replies allowed.