perror() — Print Error Message
Format
#include <stdio.h>
void perror(const char *string);
Language Level
ANSI
Threadsafe
Yes
Description
The perror()
function
prints an error message to stderr
. If string is
not NULL and does not point to a null character, the string
pointed to by string is printed to the standard
error stream, followed by a colon and a space. The message associated
with the value in errno is then printed followed by a new-line
character.
To produce accurate results, you should ensure that the perror()
function
is called immediately after a library function returns with an error;
otherwise, subsequent calls might alter the errno value.
Return Value
There is no return value.
The value of errno can be set to:
- Value
- Meaning
- EBADDATA
- The message data is not valid.
- EBUSY
- The record or file is in use.
- ENOENT
- The file or library cannot be found.
- EPERM
- Insufficient authorization for access.
- ENOREC
- Record not found.
- EIOERROR
- A non-recoverable I/O error occurred.
- EIORECERR
- A recoverable I/O error occurred.
Example
This example tries to open a stream.
If
fopen()
fails,
the example prints a message and ends the program. #include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fh;
if ((fh = fopen("mylib/myfile","r")) == NULL)
{
perror("Could not open data file");
abort();
}
}