What is perror ?
The C library function void perror(const char *str) prints a descriptive error message to stderr.First the string str is printed, followed by a colon then a space.
Str = User string.
what is strerror ?
The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum.Possibly using the LC_MESSAGES part of the current locale to select the appropriate language. (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(). No library function, including perror(3), will modify this string.
Return value:
The strerror() and the GNU-specific strerror_r() functions return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.Example:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define BUF_64 64
int main()
{
FILE *fp = NULL;
char strerr_buf[BUF_64] = {'\0'};
int ret = 0;
/* 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: ");
ret = strerror_r(errno, strerr_buf, sizeof(strerr_buf));
if (ret) {
printf("Failed to convert errno to string ret <%d> \n", ret);
}
printf("velraj errno <%d> value (%s) value using _r <%s> \n", errno, strerror(errno), strerr_buf);
return(-1);
}
fclose(fp);
printf("velraj errno = 2 value (%s)\n", strerror(2));
return(0);
}
Output:
Error: : No such file or directoryvelraj errno <2> value (No such file or directory) value using _r <No such file or directory>
No comments:
Post a Comment