473,388 Members | 1,383 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

printing error messages

gsa
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.

Jun 27 '08 #1
26 2171
In article <a1**********************************@j33g2000pri. googlegroups.com>,
gsa <hs****@gmail.comwrote:
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.
See the documentation on perror(). (Note: perror has some subtle
limitations that can make it a better idea to use the lower-level
equivilents... which you will likely find references to in the
perror() documentation.)
--
"To all, to each! a fair good-night,
And pleasing dreams, and slumbers light" -- Sir Walter Scott
Jun 27 '08 #2
In article <a1**********************************@j33g2000pri. googlegroups.com>,
gsa <hs****@gmail.comwrote:
>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.
perror() may be what you're looking for.
I don't believe fopen is required to set errno when it fails, but on
every implementation I've encountered it does. (That may be influenced
by the fact that most of the implementations I've used are unixy, and I
think POSIX *does* require the underlying system calls to set errno.)
dave

--
Dave Vandervies dj3vande at eskimo dot com
I've been curious about what 'lingua franca' actually meant for a while, and
this seemed the perfect excuse to find out - and it appears to have worked.
comp.lang.c will never cease to amaze me. --Richard Heathfield
Jun 27 '08 #3
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.

--
Er*********@sun.com
Jun 27 '08 #4
gsa
Thanks all! Did it with function error().

Jun 27 '08 #5
gsa
I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

Jun 27 '08 #6
In article <dd**********************************@l17g2000pri. googlegroups.com>,
gsa <hs****@gmail.comwrote:
>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!
Note that error() is not portable; the man page on my system says:
These functions and variables are GNU extensions, and should not be
used in programs intended to be portable.
So if you plan to use this program anywhere other than on Linux, you
should probably use the portable building blocks (error() appears to be
built on strerror(), exit(), and a few stdio functions, plus an
extension to get the value of argv[0] somewhere outside of main())
instead of the GNU convenience wrapper.
(In your case, it may be acceptable to plan to write your own version
of error() when you want to run somewhere other than Linux, since it
gives you a one-line call that does a set of things that's not-quite-
trivial to write yourself. But you should be aware of the
nonportability and make sure that the benefits do indeed exceed the
costs.)
dave

--
Dave Vandervies dj3vande at eskimo dot com
I've been curious about what 'lingua franca' actually meant for a while, and
this seemed the perfect excuse to find out - and it appears to have worked.
comp.lang.c will never cease to amaze me. --Richard Heathfield
Jun 27 '08 #7
I personally use fprintf. For eg:

typedef struct xyz_struct
{
..
}*xyzptr;

void foo()
{
xyzptr p;

p = malloc(sizeof(*p));

if(p == NULL)
frpintf("Unable to allocate memory: %s %d %s", __FILE__,
__LINE__,__func__);
..
}

I'm not sure if this is a good method though
Jun 27 '08 #8

"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!
For my 2 cents worth exit(1) isn't portable. Try exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working and non
working program.

Bill
Jun 27 '08 #9
"Bill Cunningham" <no****@nspam.comwrites:
"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

For my 2 cents worth exit(1) isn't portable. Try exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working and non
working program.

Bill
I do not believe you. I would be interested in seeing this program that
suddenly magically worked when you change the code you call exit with.
Jun 27 '08 #10
Bill Cunningham wrote:
>
"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working and non
working program.
exit(1) didn't work? What's your system and what exactly happened, i.e.,
what was the behaviour that made you conclude that exit(1) failed.

Jun 27 '08 #11
santosh <sa*********@gmail.comwrites:
Bill Cunningham wrote:
>>
"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>>>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working and non
working program.

exit(1) didn't work? What's your system and what exactly happened, i.e.,
what was the behaviour that made you conclude that exit(1) failed.
He is trolling. I replied before realising who it was.
Jun 27 '08 #12
"Bill Cunningham" <no****@nspam.comwrites:
"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from stdlib.h. For me it has made the difference
between a working and non working program.
Really?

You're absolutely right that exit(1) isn't portable, and
exit(EXIT_FAILURE) is preferred.

But it won't affect the behavior of the program itself until it
terminates -- and on most systems you're likely to be using
(including, I'm fairly sure, all variations of Unix and Windows),
exit(1) and exit(EXIT_FAILURE) happen to behave the same way. (You're
not using VMS, are you?)

Perhaps you happened to make some other fix at the same time that you
changed the exit() call.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #13
santosh wrote:
Bill Cunningham wrote:
.... snip ...
>
>For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working
and non working program.

exit(1) didn't work? What's your system and what exactly happened,
i.e., what was the behaviour that made you conclude that exit(1)
failed.
"exit(1);" never is portable, and has absolutely no guarantees.
Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #14
CBFalconer <cb********@yahoo.comwrites:
santosh wrote:
>Bill Cunningham wrote:
... snip ...
>>
>>For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working
and non working program.

exit(1) didn't work? What's your system and what exactly happened,
i.e., what was the behaviour that made you conclude that exit(1)
failed.

"exit(1);" never is portable, and has absolutely no guarantees.
Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.
Bill is of course 100% correct that exit(1) is not portable. But
that's not all he said. He also said that it "has made the difference
between a working and non working program". I find that claim
surprising (for reasons that happen to be beyond the scope of the C
standard).

Do you have reason to believe that it actually did make such a
difference?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 27 '08 #15
On Jun 1, 3:06 am, CBFalconer <cbfalco...@yahoo.comwrote:
santosh wrote:
Bill Cunningham wrote:

... snip ...
For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working
and non working program.
exit(1) didn't work? What's your system and what exactly happened,
i.e., what was the behaviour that made you conclude that exit(1)
failed.

"exit(1);" never is portable, and has absolutely no guarantees.
Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.
AFAIK exit(1) has guarantees about the behavior of the program. It
doesn't guarantee a meaningful value to be returned.
Jun 27 '08 #16
CBFalconer wrote:
santosh wrote:
>Bill Cunningham wrote:
... snip ...
>>
>>For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working
and non working program.

exit(1) didn't work? What's your system and what exactly happened,
i.e., what was the behaviour that made you conclude that exit(1)
failed.

"exit(1);" never is portable, and has absolutely no guarantees.
Of course. But I'm interested to hear the details of the implementation
under which exit(1) resulted in a "non working program", as Bill
claims.
Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.
It should be EXIT_SUCCESS, not EXIT_OK.

Jun 27 '08 #17
vi******@gmail.com writes:
On Jun 1, 3:06 am, CBFalconer <cbfalco...@yahoo.comwrote:
>santosh wrote:
Bill Cunningham wrote:

... snip ...
>For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working
and non working program.
exit(1) didn't work? What's your system and what exactly happened,
i.e., what was the behaviour that made you conclude that exit(1)
failed.

"exit(1);" never is portable, and has absolutely no guarantees.
Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.
AFAIK exit(1) has guarantees about the behavior of the program. It
doesn't guarantee a meaningful value to be returned.
What do you mean AFAIK? What do you expect to go wrong with the program
when exit is called? And talk in standard C in this case - I am not
concerned about return codes to system calls for example.

Jun 27 '08 #18
santosh wrote:
CBFalconer wrote:
.... snip ...
>
>Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.

It should be EXIT_SUCCESS, not EXIT_OK.
True. I plead short-term-memory loss.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #19
CBFalconer wrote:
santosh wrote:
>CBFalconer wrote:
... snip ...
>>Bill is right here, the only guaranteed values for exit are 0,
EXIT_OK, and EXT_FAILURE. The latter two require include stdlib.h.
It should be EXIT_SUCCESS, not EXIT_OK.

True. I plead short-term-memory loss.
Senior moments? Old-Timers Disease? Don't worry about it. You've
forgotten more than these youngsters know. You also know stuff that they
will never even learn. Experience counts!

Hang in there.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Jun 27 '08 #20
Eric Sosman wrote:
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.
Also a small additional point. You might want to set errno to zero just
before a call to a library function. Since library functions are
guaranteed to not store zero in errno, you can be sure that the value
you are reading (and it's associated error message) has been set by the
previous function call, and not some "left over" value.

Jun 27 '08 #21
gsa wrote:
I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!
There is no standard function called error. You are using an
implementation specific extension which might not be available under
the next compiler you try your code with.

Jun 27 '08 #22
santosh wrote:
Bill Cunningham wrote:
>>
"gsa" <hs****@gmail.comwrote in message
news:dd**********************************@l17g2000 pri.googlegroups.com...
>>>I just stuck the error function call in the if block and it worked.

if((fp = fopen(stretchesFile, "w")) == NULL) {
error(1, errno, "could not open file %s", stretchesFile);
exit(1);
}

Thanks again for your help!!

For my 2 cents worth exit(1) isn't portable. Try
exit(EXIT_FAILURE) from
stdlib.h. For me it has made the difference between a working and non
working program.

exit(1) didn't work? What's your system and what exactly happened, i.e.,
what was the behaviour that made you conclude that exit(1) failed.
On my Binford DS 6100, exit(), when passed these values,
behaves as follows:

EXIT_SUCCESS (0)
return to host environment indicating success

EXIT_FAILURE (42)
return to host environment indicating failure

EXIT_NOP (1)
return to the function that called exit()

[further documented exit codes omitted]

Does that violate any standards?

Jun 27 '08 #23
Baboon wrote:
[...]
On my Binford DS 6100, exit(), when passed these values,
behaves as follows:

EXIT_SUCCESS (0)
return to host environment indicating success

EXIT_FAILURE (42)
return to host environment indicating failure

EXIT_NOP (1)
return to the function that called exit()

[further documented exit codes omitted]

Does that violate any standards?
Yes. The specification of exit() requires that it must
terminate the program -- well, all right, a perverse atexit()
function could run indefinitely, but exit() does not return
to its caller. 7.20.4.3p6.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #24
Eric Sosman wrote:
Baboon wrote:
>[...]
On my Binford DS 6100, exit(), when passed these values,
behaves as follows:

EXIT_SUCCESS (0)
return to host environment indicating success

EXIT_FAILURE (42)
return to host environment indicating failure

EXIT_NOP (1)
return to the function that called exit()

[further documented exit codes omitted]

Does that violate any standards?

Yes. The specification of exit() requires that it must
terminate the program -- well, all right, a perverse atexit()
function could run indefinitely, but exit() does not return
to its caller. 7.20.4.3p6.
I think it's an extension, and as long as he doesn't ever write
"EXIT_NOP" his programs will comply.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #25
CBFalconer wrote:
Eric Sosman wrote:
>Baboon wrote:
>>[...]
On my Binford DS 6100, exit(), when passed these values,
behaves as follows:

EXIT_SUCCESS (0)
return to host environment indicating success

EXIT_FAILURE (42)
return to host environment indicating failure

EXIT_NOP (1)
return to the function that called exit()

[further documented exit codes omitted]

Does that violate any standards?
Yes. The specification of exit() requires that it must
terminate the program -- well, all right, a perverse atexit()
function could run indefinitely, but exit() does not return
to its caller. 7.20.4.3p6.

I think it's an extension, and as long as he doesn't ever write
"EXIT_NOP" his programs will comply.
If exit(any_int_whatsoever) returns to its caller, I think
it's a non-conforming "extension:"

7.20.4.3 The exit function
...
/5/ Finally, control is returned to the host environment.
[...description of Standard-defined status values...]
Otherwise the status returned is implementation-defined.

/6/ The exit function cannot return to its caller.

The only thing the argument value governs is the nature of the
status indication. The first sentence of p5 is not conditional,
nor does anything in p5 (or elsewhere in 7.20.4.3) annul p6.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #26
On 30 May, 19:04, pereges <Brol...@gmail.comwrote:
I personally use fprintf [for error reporting]. For eg:
<snip>
void foo()
{
* xyzptr p;

* p = malloc(sizeof(*p));

* if(p == NULL)
* * frpintf("Unable to allocate memory: %s %d %s", __FILE__,
__LINE__,__func__);
* ..

}

I'm not sure if this is a good method though

It's not a bad idea, though it might be a good idea to
specify a file (stream) to write to
frpintf(stderr, "Unable to allocate memory: %s %d %s", __FILE__,
__LINE__,__func__);

and note __func___ is only available with the latest standard
(C99) which is still only patchily supported.
--
Nick Keighley
Jun 27 '08 #27

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Chris | last post by:
Hello all, I wish to automate printing of PDF documents in a C# application. Is there an Adobe .net object? I tried to create a reference to the COM Object Adobe Type Library, but I get error...
2
by: jim_geissman | last post by:
I have a script or SP that takes a very long time to perform multiple tasks, and after each one there is a PRINT statement that shows the time and what was just accomplished, to help me monitor...
5
by: zeljko.markic | last post by:
I want to implement silent printing in my project to print reports programmatically, so that a user will not see any pop-up messages to do with the printing process. For instance, I want to hide...
1
by: hamil | last post by:
I am trying to print a graphic file (tif) and also use the PrintPreview control, the PageSetup control, and the Print dialog control. The code attached is a concatination of two examples taken out...
0
by: melanieab | last post by:
Hi, When the print button is clicked, I save a snapshot of the screen to a bitmap file. Graphics currentTab = this.CreateGraphics(); Size s = this.Size; Bitmap memoryImage = new Bitmap(s.Width -...
0
by: Hank | last post by:
We have been printing pdf files through Adobe, from Access for several years. Adobe version 5.0 is currently installed. Recently we have received PDF files that were created under the Adobe 7.0...
0
by: m23 | last post by:
Hi, I have an access 2000 application that is run as an mde from CITRIX. Each user running the application gets their own copy of the mde. access is just used as the front end forms the actual...
2
by: Brad Pears | last post by:
I have some sample code that uses the print dialog, print preview and a print direct options. If I select print preview and then click the printer icon from that, the document prints. If I...
3
by: tbest4475 | last post by:
AIX I have a set of commands that run and if a difference is found it prints a message to an array and then sends that array in an email. certain messages are not printing the new line after the...
18
by: Brett | last post by:
I have an ASP.NET page that displays work orders in a GridView. In that GridView is a checkbox column. When the user clicks a "Print" button, I create a report, using the .NET Framework printing...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.