Re: When to use "perror" and "fprintf"

From: Dan Pop (Dan.Pop_at_cern.ch)
Date: 05/11/04


Date: 11 May 2004 14:52:13 GMT

In <kcQlc.185$WS3.72@reader1.news.jippii.net> Lars Wirzenius <liw@iki.fi> writes:

>Darrell Grainger <darrell@NOMORESPAMcs.utoronto.ca.com>:
>> For example, strtol will return LONG_MAX or LONG_MIN if a string is out of
>> range and set errno to ERANGE. So if strtol fails due to out of range, I
>> would use perror.
>
>I have found that it is useful, in practice, to include the value of
>errno in the output. These days, the error message output by perror
>is often translated. This is good for the user, as they get an error
>in a language they understand, but bad for me, if it is in a language
>I do not understand. Therefore, I tend not to use perror and instead
>use something like this:
>
> fprintf(stderr, "Error: Can't open file: %d: %s\n",
> errno, strerror(errno));
>
>If there is an error, I can look up the reason using the numerical
>error code regardless of what the text looks like.

This doesn't work for portable code, as the user's implementation need not
use the same errno codes as yours. Call strerror(errno) twice, once in
the user's locale, the other time in the "C" locale and compare the
two strings. If they're identical, display only one, otherwise display
both and ask the user to quote the English one verbatim.

Dan

-- 
Dan Pop
DESY Zeuthen, RZ group
Email: Dan.Pop@ifh.de


Relevant Pages

  • Re: When fopen() fails
    ... >> If fopen fails, is there a way to know why? ... >can use perror() to print that information as a readable string. ... reset errno, call fopen, if it fails and errno is non-null you can assume ... Dan Pop ...
    (comp.lang.c)
  • Re: perror sets errno to "Illegal Seek"
    ... Calling perror() again may print out anything, ... you call a library function you can't depend on errno not being touched. ... *if* the function reports failure *and* the specification says the function ... not ESUCCESS otherwise". ...
    (comp.os.linux.development.apps)
  • Re: How to write to a file including full directory in C under Unix?
    ... copy the literal into a buffer and then use the buffer (for ... Use perror() or errno to show what was the error. ... have an appropriate newsgroups line in your header for your mail to be seen, ...
    (comp.lang.c.moderated)
  • Re: I dont understand the errors on this fork/exec
    ... First error code:: Success ... How come the first perror() prints 'Success'. ... perrorcan change the value of errno. ...
    (comp.unix.programmer)
  • Re: VC++ 2005 beta1 fails with pthreads benchmark tests
    ... >>> It is the last assert which fails in the first of the failing test ... >> Why should 'perror' be expected to cause an 'EGAIN' error? ... > It is not perror which sets errno ...
    (microsoft.public.dotnet.languages.vc)