C programming strerror string.h


char *strerror(int errnum);

Parameters:
errnum -An error number.

Return type
char* -Returns a pointer to the string,the contents of which are locale-specific.The array pointed to shall not be modified by the program,but may be over written by a subsequent call to the ‘strerror’ function.

The function ‘strerror’ of <string.h> prints an error message based on the error number:errnum,passed to the function.Note the C library has a of associating an error message with a corresponding number.When any function encounter an error a number matching that error type is generated.And when we call ‘strerror’ the error number generated is passed to the function and it will mapped the number to the corresponding message and print out accordingly.Typically,the values for ‘errnum’ come from ‘errno’,but ‘strerror’ shall map any value of type ‘int’ to a message.Consider the code example below.

Code example

#define sz 1024

int main(int argc , char **argv )
{
FILE *fp;

char msg[sz];

if( (fp=fopen( “some_file” , “r”))==NULL ) //the ‘some_file’ is a non-existing file
{
int errnum = errno; //get the error number

ret = strerror(errnum);

printf(“Error:%s”, ret);
}

getchar( );
return 0;
}

Output in VS in my case,

Error:No such file or directory

Since the file name “some_file” we have passed is some non-existing file,we get the error message as “No such file or directory” which makes sense.


Related links

->C memset string.h

->C strlen string.h

->C fopen stdio.h