Re: printing error messages
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Fri, 30 May 2008 12:36:48 -0400
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
.
- References:
- printing error messages
- From: gsa
- printing error messages
- Prev by Date: Re: malloc()/realloc() - have I got this right?
- Next by Date: Re: Determine the size of malloc
- Previous by thread: Re: printing error messages
- Next by thread: Help with atoi function for a numero program.
- Index(es):
Relevant Pages
|