This blog is under construction

Sunday, 29 April 2012

strerror example in C

 Header file:
    string.h

Synopsis:
   char *strerror(int num);

Description:
   It returns pointer to the pre-defined string corresponding to the errno num.


strerror function C example:


  #include<stdio.h>
  #include<string.h>
  #include<errno.h>
  int main(int argc, char **argv) {
        FILE *fp;
        char *errmsg;
        fp = fopen(argv[1], "r");

        if (fp == NULL) {
                /* errno - available in errno.h */
                errmsg = strerror(errno);
                printf("Error message=> %s\n", errmsg);
                return;
        }
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Error no: 14 & message: Bad address


The above program takes file name as command line argument.  But, we haven't passed any command line argument.  So, fopen would return NULL and set errno(available in errno.h) to 14.  The error message corresponds to errno 14 is obtained using strerror() function.

No comments:

Post a Comment