answersLogoWhite

0

The perror() function is used to print a user-defined error message to stderr. Consider the following:

Example:

#include

int main ()

{

FILE * pFile;

pFile=fopen ("missing.txt","rb");

if (pFile==NULL)

perror ("missing.txt");

else

fclose (pFile);

return 0;

}

Possible Output:

missing.txt: No such file or directory

We can achieve the exact same effect with a more verbose fprintf() statement, such that the following are equivalent:

perror ("Error");

fprintf (stderr, "Error: %s\n", strerror (errno));

The following are also equivalent:

perror (NULL);

fprintf (stderr, strerror (errno));

We typically use fprintf() statement when we need to print messages other than those provided by strerror and/or wish to redirect the output to a device other than stderr. But for all error messages based upon the thread-local errno, perror is more concise and reduces the chances of introducing errors through typos (such as accidently redirecting errors to stdout instead of stderr).

User Avatar

Wiki User

8y ago

What else can I help you with?