472,805 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

fopen and fclose?

if fopen failed, does it necessary to call fclose?

I see an example like this:
....
stream = fopen(...);
if(stream == NULL)
{
....
}
else
{
....
}
fclose(stream);
....

By my understanding, it should like this:
....
stream = fopen(...);
if(stream == NULL)
{
....
}
else
{
....
fclose(stream);
}

Feb 3 '06 #1
17 14679
It should be like this:

stream = fopen(...);
if (stream == NULL)
{
...
}
else
{
...
fclose(stream);
}

fclose'ing a NULL pointer is undefined and could cause problems.
fclose a stream ONLY iff it is a valid open stream.

Feb 3 '06 #2
kathy wrote:
if fopen failed, does it necessary to call fclose?
It doesn't hurt anything to call fclose with a null pointer, and the
function will return an error code if it fails to close the supplied
file.

I see an example like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
}
fclose(stream);
...

By my understanding, it should like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
fclose(stream);
}


Your way is preferable, IMHO, but I think either is legal. Better still
might be to use std::fstream instead. :-)

Cheers! --M

Feb 3 '06 #3
kathy wrote:
if fopen failed, does it necessary to call fclose?
No. And actually I can't find any description of what's going to happen
if you pass a null pointer to 'fclose'. Conclusion: it's undefined
behaviour and should be avoided. IOW, you must _not_ call 'fclose' for
a pointer obtained from 'fopen' if opening failed (and null pointer is
returned).
[..]


V
Feb 3 '06 #4
mlimber wrote:
kathy wrote:
if fopen failed, does it necessary to call fclose?


It doesn't hurt anything to call fclose with a null pointer


I stand corrected.

Feb 3 '06 #5
mlimber wrote:
mlimber wrote:
kathy wrote:
if fopen failed, does it necessary to call fclose?


It doesn't hurt anything to call fclose with a null pointer


I stand corrected.


Hmm. On second... er, third thought, I'm not sure what the standard
mandates, but the IRIX 6.5 manpages do say: "For fclose, EOF is
returned if stream is NULL, or stream is not active, or there was an
error when flushing buffered writes, or there was an error closing the
underlying file descriptor."

Cheers! --M

Feb 3 '06 #6
mlimber wrote:

Hmm. On second... er, third thought, I'm not sure what the standard
mandates, but the IRIX 6.5 manpages do say: "For fclose, EOF is
returned if stream is NULL, or stream is not active, or there was an
error when flushing buffered writes, or there was an error closing the
underlying file descriptor."


IRIX man pages are not the Standard. There's no similar wording in
either the C or C++ standards.

Here's the wording from the C99 draft standard:

7.19.5.1 The fclose function

Synopsis

[#1]

#include <stdio.h>
int fclose(FILE *stream);

Description

[#2] The fclose function causes the stream pointed to by
stream to be flushed and the associated file to be closed.
Any unwritten buffered data for the stream are delivered to
the host environment to be written to the file; any unread
buffered data are discarded. The stream is disassociated
from the file. If the associated buffer was automatically
allocated, it is deallocated.

Returns

[#3] The fclose function returns zero if the stream was
successfully closed, or EOF if any errors were detected.

Brian
--
If televison's a babysitter, the Internet is a drunk librarian who
won't shut up.
-- Dorothy Gambrell (http://catandgirl.com)
Feb 4 '06 #7
Default User <de***********@yahoo.com> wrote:
7.19.5.1 The fclose function Returns

[#3] The fclose function returns zero if the stream was
successfully closed, or EOF if any errors were detected.


Out of interest, could one not assume that "any error" will include
having passed 0 to fclose .. ?

regards
--
jb

(reply address in rot13, unscramble first)
Feb 4 '06 #8
Jakob Bieling wrote:
Default User <de***********@yahoo.com> wrote:
7.19.5.1 The fclose function

Returns

[#3] The fclose function returns zero if the stream was
successfully closed, or EOF if any errors were detected.


Out of interest, could one not assume that "any error" will include
having passed 0 to fclose .. ?


Do you have some sort of support for that?

I think the fact that it differs from the implementation-specific man
page should tell you what you need to know.

Closing a null FILE* is UB.
Brian
--
If televison's a babysitter, the Internet is a drunk librarian who
won't shut up.
-- Dorothy Gambrell (http://catandgirl.com)
Feb 4 '06 #9
On 3 Feb 2006 12:05:06 -0800, "kathy" <yq*****@yahoo.com> wrote:
if fopen failed, does it necessary to call fclose?

I see an example like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
}
fclose(stream);
...

By my understanding, it should like this:
...
stream = fopen(...);
if(stream == NULL)
{
...
}
else
{
...
fclose(stream);
}

else {
....
if (fclose(stream) == 0) {
// success
} else {
// error
}
}

Best wishes,
Roland Pibinger
Feb 4 '06 #10
Default User <de***********@yahoo.com> wrote:
Jakob Bieling wrote:
Default User <de***********@yahoo.com> wrote:
7.19.5.1 The fclose function
Returns

[#3] The fclose function returns zero if the stream was
successfully closed, or EOF if any errors were detected.


Out of interest, could one not assume that "any error" will include
having passed 0 to fclose .. ?


Do you have some sort of support for that?


The only support is that paragraph you cited, since I do not call
fclose with a 0-pointer either (nor would I encourage anyone to do so).

Guess I am just complaining about them writing "any error", when in
fact passing a 0-pointer is not covered.
I think the fact that it differs from the implementation-specific man
page should tell you what you need to know.

Agreed.

regards
--
jb

(reply address in rot13, unscramble first)
Feb 4 '06 #11
Jakob Bieling wrote:

Guess I am just complaining about them writing "any error", when in
fact passing a 0-pointer is not covered.

Many functions, especially those inherited from C, accept null pointers
without defined behavior. Notably most of the C-style string functions.

Brian

Feb 5 '06 #12
Default User wrote:
Jakob Bieling wrote:

Guess I am just complaining about them writing "any error", when in
fact passing a 0-pointer is not covered.

Many functions, especially those inherited from C, accept null pointers
without defined behavior. Notably most of the C-style string functions.

Absolutely, completely wrong.

7.1.4 of the C standard says that:

If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address
space of the program, OR A NULL POINTER, or a pointer to on-modifiable
storage when the corresponding parameter is not const-qualified) or a
type (after promotion) not expected by a function with variable number
of arguments, the behavior is undefined.

The string functions as does fclose, do not specify behavior for
being passed null behavior, hence by 7.1.4 the behavior is undefined.
Feb 14 '06 #13
Ron Natalie wrote:
Default User wrote:
Jakob Bieling wrote:

Guess I am just complaining about them writing "any error", when in
fact passing a 0-pointer is not covered.

Many functions, especially those inherited from C, accept null pointers
without defined behavior. Notably most of the C-style string functions.

Absolutely, completely wrong.

7.1.4 of the C standard says that:

If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address
space of the program, OR A NULL POINTER, or a pointer to on-modifiable
storage when the corresponding parameter is not const-qualified) or a
type (after promotion) not expected by a function with variable number
of arguments, the behavior is undefined.

The string functions as does fclose, do not specify behavior for
being passed null behavior, hence by 7.1.4 the behavior is undefined.


I think you two are in violent agreement.

:P

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Feb 14 '06 #14

Ron Natalie wrote:
Default User wrote:
Jakob Bieling wrote:

Guess I am just complaining about them writing "any error", when in
fact passing a 0-pointer is not covered.

Many functions, especially those inherited from C, accept null pointers
without defined behavior. Notably most of the C-style string functions.

Absolutely, completely wrong.


I don't think so!
7.1.4 of the C standard says that:

If an argument to a function has an invalid value (such as a value
outside the domain of the function, or a pointer outside the address
space of the program, OR A NULL POINTER, or a pointer to on-modifiable
storage when the corresponding parameter is not const-qualified) or a
type (after promotion) not expected by a function with variable number
of arguments, the behavior is undefined.
Which is what I said, more or less.
The string functions as does fclose, do not specify behavior for
being passed null behavior, hence by 7.1.4 the behavior is undefined.


That's what I said, "without defined behavior".

I believe you misread what I wrote. Probably my phrasing wasn't the
best.

Brian

Feb 14 '06 #15
Ben Pope wrote:
Ron Natalie wrote:
Default User wrote:
Many functions, especially those inherited from C, accept null
pointers without defined behavior. Notably most of the C-style
string functions.
The string functions as does fclose, do not specify behavior for
being passed null behavior, hence by 7.1.4 the behavior is
undefined.


I think you two are in violent agreement.

I believe so. My phrasing "without defined behavior" probably threw Ron
off in his reading.

I might screw up in the details of C++, but I'm unlikely to make a
fundamental error in C :)

Brian

Feb 14 '06 #16
Default User wrote:
Ben Pope wrote:
Ron Natalie wrote:
Default User wrote: Many functions, especially those inherited from C, accept null
pointers without defined behavior. Notably most of the C-style
string functions. The string functions as does fclose, do not specify behavior for
being passed null behavior, hence by 7.1.4 the behavior is
undefined.

I think you two are in violent agreement.

I believe so. My phrasing "without defined behavior" probably threw Ron
off in his reading.


Yes there term "accept" allowed me to gloss over the difference between
"defined" and "undefined". We are in "violent agreement."
Feb 15 '06 #17
Ron Natalie wrote:
Default User wrote:

I believe so. My phrasing "without defined behavior" probably threw
Ron off in his reading.


Yes there term "accept" allowed me to gloss over the difference
between "defined" and "undefined". We are in "violent agreement."


I was trying to avoid saying the Standard said it was UB, because in
most of these cases it just doesn't address what happens when you pass
in NULL. So I ended up with fairly clunky language that needed a
rewrite editor.

Brian
Feb 15 '06 #18

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

Similar topics

1
by: Martin Lucas-Smith | last post by:
I wrote the function below as part of a larger class. The fopen stage works, and, as according to the documentation at www.php.net/fopen that succesfully creates a new file. The fwrite stage...
4
by: JDJones | last post by:
I'm trying to write a script that will read from a text list of songs that I burned onto my CD (Albums011.txt), then write to the database text the new text made ready for inserting into a...
2
by: Thomas Baruchel | last post by:
Hi, wondering about: func1: setjmp() ; func2(); func2: {FILE *f; f = fopen(); func3(); fclose(f)} func3 : if() longjmp; else return; Note that FILE *fis a local variable in func2.
14
by: Aaron Couts | last post by:
I have a program that writes to a log file. It's compiled on RH Linux 7.3 (Kernel 2.4.18-18.7). It's using fopen in append mode. When the file reaches 51200000 bytes in size, the program will no...
7
by: git_cs | last post by:
Hey, guys and gals Somedays ago, I had asked for the DES algorithm in C language. Although I have written the algorthim in C myself, I am facing a peculiar problem, which I hope some of u guys and...
3
by: Patrice | last post by:
Hi, I would to call fopen function several time in my application. This application permits to read files which path is registered in a configuration file. For exemple: File 1 = toto.txt File 2...
19
by: lihua | last post by:
Hi, Group! I got one question here: We all know that fclose() must be called after file operations to avoid unexpected errors.But there are really cases when you forget to do that!Just like...
20
by: David Mathog | last post by:
A program of mine writes to a tape unit. Output can be either through stdout or through a file opened with fopen(). When all the data is transferred to tape the program needs to close the output...
25
by: subramanian100in | last post by:
Consider the following program: #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv) { if (argc != 2) { printf("Usage: <program-name<text-file>\n");
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.