Re: printing error messages



gsa wrote:
Hi,
I am new to C so please bear with my stupid questions. I am
trying to open a file to write, but the code complains that it is
unable to do so. How do I get C to print the reason it is failing?
Something like the $! function in perl. Thanks a lot for all your
help.

FILE *stream = fopen(filename, mode);
if (stream == NULL) {
perror(filename);
... whatever else ...
}

This is not absolutely airtight, because fopen() is not
*required* to describe its reason for failing by storing a
value in `errno'. So there's a chance you'll get some
completely bogus "reason" for the failure, and that could
confuse the person reading the message. In my experience,
most C implementations *do* set `errno' when fopen() fails,
so I feel the benefit of displaying what `errno' says outweighs
the risk that what it says might be nonsense.

Two warnings: First, display information from `errno'
only after you've determined that there's been a failure;
`errno' itself is not a failure-detection mechanism. Second,
don't call other functions between the point of failure and
the point when you call perror(), because they may change the
value of `errno' even on successful calls.

--
Eric.Sosman@xxxxxxx
.



Relevant Pages

  • Re: Fopen to create a file in a sub-folder (such as "Mygoal").
    ... mandating that errno shall be set by fopenafter a failure. ... and it is not possible to diagnose why? ... the hardware unlike some other languages. ...
    (comp.lang.c)
  • Re: printing error messages
    ... How do I get C to print the reason it is failing? ... value in `errno'. ... completely bogus "reason" for the failure, ... before a call to a library function. ...
    (comp.lang.c)
  • Re: Critic of the given code.
    ... length from stdin. ... I do copy the return value of realloc(), ... I considered returning a simple 1 for success or 0 for failure. ... Are user functions allowed to modify errno? ...
    (comp.lang.c)
  • Re: returning error from main()
    ... M$ has lots of their "safe" functions returning an errno_t, ... NULL on failure", not even leaving some errno mention... ... suspect theat class is small, ...
    (comp.lang.c)
  • Re: mlock() return value issue in kernel 2.6.23.17
    ... Seems SUSv3 has more requirements beyond errno return code. ... This testcase results with mlock failure with errno 14 that is EFAULT, ... [EAGAIN] ...
    (Linux-Kernel)