What is Perror in C?In C language, error detection can be done using the Perror standard library feature. Through which the user can print the description of the error message when a certain error is detected in the code to the Standard Error Stream(stderr), which is based on the variable "errno", which is declared globally in the program. The function prototype for Perror is as follows: The "perror" function takes a string argument (s) that is typically used to provide additional information about the error. A descriptive error message is then printed to stderr. The current value of the "errno" variable, along with the value of the string supplied by "s" (if mentioned), are used to identify this message's brief textual explanation of the mistake. The error's textual description is formatted as "s:error_message", with error_message denoting the actual error. Example:Here's an example usage of Perror: Output: ERROR! Error: No such file or directory Explanation: In this example, the program is trying to open a file that does not exist. If the fopen function fails, the file will be NULL, and perror will be called with the string "Error". The perror function then prints a descriptive error message to stderr. B. "Error:No such file or directory". Note: The header files, namely <stdio.h> and <errno.h> must be included in the code inorder to use this Perror and variable named error.The Perror function in C is used to provide informative error messages when a function encounters an error. It is particularly useful for diagnosing and debugging problems during program execution. Here are some key uses and benefits of perror:
By employing perror in your C programs, you can enhance error reporting, simplify debugging, and improve the overall robustness of your code. Example 1: Division by ZeroOutput: Error: Division by zero Explanation: In this example, the program attempts to divide the dividend by divisor, which is set to zero. This results in a division by zero error. Before performing the division, errno is explicitly set to zero to ensure that any previous error codes are cleared. After the division, if errno is non-zero, perror is called with the string "Error". The error message "Error: Division by zero" is then printed. Example 3: Invalid Memory AllocationOutput: Error: Cannot allocate memory Next TopicDifference Between Array and String in C |