perror() in C (original) (raw)
Last Updated : 3 Feb, 2025
In C, **perror() is a built-in function used to display a custom text description of the error code, which is stored in the system variable **errno.
**Example:
C `
#include <stdio.h>
int main() { FILE *fptr = fopen("gfg.text", "rw+");
// print error
if(fptr == NULL)
perror("An error occurred");
return 0;}
`
**Output
An error occurred: No such file or directory
Table of Content
Syntax
**clearerr() is a standard library function defined in <stdio.h> file.
perror("message");
This function does not return any value.
Examples of perror()
The following examples demonstrate the use of perror() in our C programs:
Handle Memory Allocation Error
C `
#include <stdio.h> #include <stdlib.h>
int main() { size_t size = 1e18; void *ptr = malloc(size);
if (ptr == NULL) {
// Print memory allocation error using
// perror()
perror("Memory allocation failed");
}
else {
free(ptr);
}
return 0;}
`
**Output
Memory allocation failed: Cannot allocate memory
Handle Insufficient Permission Error
C `
#include <stdio.h>
int main() { FILE *file = fopen("/root/protected.txt", "w");
if (file == NULL) {
perror("Error creating file");
return 1;
}
fclose(file);
return 0;}
`
**Output
Error creating file: Permission denied