Wednesday, 27 June 2018

Convert Error no(errno) into a string value

NAME

       strerror, strerror_r - return string describing error number

SYNOPSIS

 #include <string.h>
       char *strerror(int errnum);
       int strerror_r(int errnum, char *buf, size_t buflen);
                   /* XSI-compliant */
       char *strerror_r(int errnum, char *buf, size_t buflen);
                   /* GNU-specific */
   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
       The XSI-compliant version of strerror_r() is provided if:
       (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
       Otherwise, the GNU-specific version is provided.
     

DESCRIPTION


  • The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum.
    • For example, if errnum is EINVAL, the returned description will "Invalid argument".
  • This string must not be modified by the application, but may be modified by a subsequent call to strerror()
  • The  strerror_r()  function  is  similar to strerror(), but is thread safe. 

RETURN VALUE

    Return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.

Program:

/* error number into an String value program by Velraj.K
   Check : http://velrajcoding.blogspot.in
  */


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

int main()
{
    FILE *fp;

    /* first rename if there is any file */
    rename("file.txt", "newfile.txt");

    /* now let's try to open same file */
    fp = fopen("file.txt", "r");
    if( fp == NULL ) {
        perror("Error: ");
        printf("velraj errno = %d value (%s)\n", errno, strerror(errno));
        return(-1);
    }
    fclose(fp);

    return(0);

}

Output:

sample$ ./a.out
Error: : No such file or directory
velraj errno = 2 value (No such file or directory)


No comments:

Post a Comment