top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between strerror and perror in C?

+2 votes
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 LinkedIn 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)  
        printf("strerror:%s\n", strerror(errno));  

Print an error as a human-readable string

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

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


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.


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