Jump to content

C++ Programming/Code/Standard C Library/Functions/perror

From Wikibooks, open books for an open world

perror

[edit | edit source]
Syntax
#include <cstdio>
void perror( const char *str );

The perror() function writes str, a ":" followed by a space, an implementation-defined and/or language-dependent error message corresponding to the global variable errno, and a newline to stderr. For example:

char* input_filename = "not_found.txt";
FILE* input = fopen( input_filename, "r" );
if( input == NULL ) {
 char error_msg[255];
 sprintf( error_msg, "Error opening file '%s'", input_filename );
 perror( error_msg );
 exit( -1 );
}

If the file called not_found.txt is not found, this code will produce the following output:

Error opening file 'not_found.txt': No such file or directory

If "str" is a null pointer or points to the null byte, only the error message corresponding to errno and a newline are written to stderr.

Related topics
clearerr - feof - ferror