top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is the difference between strerror and perror in C?

+2 votes
514 views
What is the difference between strerror and perror in C?
posted Aug 18, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

perror and strerror are provided by the C language library functions used for to erno related error message, not very different usage is also simple. The biggest difference is that perror output to stderr, strerror output to stdout results.

The test code is as follows:

#include <stdio.h>  
#include <string.h>  
#include <errno.h>  

int main(int argc, char* argv[])  
{  
    FILE *fp;  
    if ((fp = fopen(argv[1], "r")) == NULL)  
    {  
        perror("perror:");  
        printf("strerror:%s\n", strerror(errno));  
    }  
    exit(0);  
}  

Print an error as a human-readable string

Prototypes
#include <stdio.h>
#include <string.h>   // for strerror()

void perror(const char *s);
char *strerror(int errnum);

Description

Since so many functions return -1 on error and set the value of the variable errno to be some number, it would sure be nice if you could easily print that in a form that made sense to you.

Mercifully, perror() does that. If you want more description to be printed before the error, you can point the parameter s to it (or you can leave s as NULL and nothing additional will be printed.)

In a nutshell, this function takes errno values, like ECONNRESET, and prints them nicely, like "Connection reset by peer."

The function strerror() is very similar to perror(), except it returns a pointer to the error message string for a given value (you usually pass in the variable errno.)

Return Value

strerror() returns a pointer to the error message string.

Example

int s;

s = socket(PF_INET, SOCK_STREAM, 0);

if (s == -1) { // some error has occurred
    // prints "socket error: " + the error message:
    perror("socket error");
}

// similarly:

if (listen(s, 10) == -1) {
    // this prints "an error: " + the error message from errno:
    printf("an error: %s\n", strerror(errno));
}
answer Aug 20, 2015 by Mohammed Hussain
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...