473,394 Members | 1,951 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,394 software developers and data experts.

How to tell a file is been close.

FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.
I know can set fp to NULL after fclose it, then check fp's value to
solve the problem.
But, if there have other methods?

May 17 '07 #1
19 1796
empriser said:
FILE *fp;

fp = fopen( ... )
fclose( fp ).
fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

How do I know if fp has been fclose.
I know can set fp to NULL after fclose it, then check fp's value to
solve the problem.
Right. When you call fclose, the value of fp becomes indeterminate,
which means that you are no longer allowed to use that value for any
purpose. So the best thing you can do is give fp a new value that you
/can/ use, and NULL is the obvious candidate.

But, if there have other methods?
No.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
May 17 '07 #2
empriser wrote:
FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.
You have to remember that you've closed it. (Or, preferably,
arrange that you don't have to care.)
I know can set fp to NULL after fclose it, then check fp's value to
solve the problem.
That doesn't help if there are other copies of `fp`s value.

A useful trick is to arrange that your file-handling code looks like:

{ FILE* fp = fopenSuitably()
; doThingsWithFile( fp )
; fclose( fp )
; }

(Don't mind my layout, I'm being experimental today.)

(Insert check on `fclose` working to taste.)

Now, this piece of code is so short it's easy to check that
you never use `fp` after its been closed. (Assuming that
`doThingsWithFile` doesn't wilfully copy `fp` elsewhere.)

And sometimes you can arrange that `doThingsWithFile` is a
function pointer. (If it needs extra state, pass that in too.)

If most of your file-handling can be done that way, you only need
to be deeply suspicious of other uses of files.

Another trick is to have a struct

struct fileAndBoolean
{ YourBooleanType closed
; FILE* fp
; }

Write file-accessing methods on `struct fileAndBoolean*`. Have them
check whether `closed` is true. Set `closed` on `close()`.

Whether these tricks are of value to you depends on your context.

--
"It's just the beginning we've seen" - Colosseum, /Tomorrow's Blues/

Hewlett-Packard Limited registered office: Cain Road, Bracknell,
registered no: 690597 England Berks RG12 1HN

May 17 '07 #3
empriser wrote:
FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.
fclose() returns 0 on success.
I know can set fp to NULL after fclose it, then check fp's value to
solve the problem.
what is the problem?

--
Tor
May 17 '07 #4
On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)
The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?

May 17 '07 #5
On May 18, 1:14 am, "christian.bau" <christian....@cbau.wanadoo.co.uk>
wrote:
On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
Error propagation and catching is a problem in C and in general
structured programming languages.
Coming back to the topic. You can check the errno. Check this:
http://man.he.net/?topic=fclose&section=all

Check this to know how to use errno: http://www.mkssoftware.com/docs/man5/errno.5.asp
http://www.unix.geek.org.uk/~arny/info/library_2.html
May 17 '07 #6
In article <11**********************@h2g2000hsg.googlegroups. com>,
christian.bau <ch***********@cbau.wanadoo.co.ukwrote:
>fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)
>The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
You can warn the user, so he doesn't delete the old version of his
data.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
May 17 '07 #7
Tor Rustad <torust_at_online.nowrote:
empriser wrote:
FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.

fclose() returns 0 on success.
Even on failure fp is still effectively closed for all intents and purposes.
fp becomes (or remains) invalid either way.
May 17 '07 #8
christian.bau said:
On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>fclose can fail. Check the return result. (Here, I'm speaking as much
to myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
As Richard T points out, you can warn the user. Also, you may still have
the data in memory, in which case you can prompt for a different
filename, suggesting to the user that he might like to specify a
different device.

"Warn the user" is the very least you can do for /any/ failure (except
one). Often you can do more, but even if you can't, at least you can
clue the user in to what is going wrong.

The one exception, of course, is where the failure is that your program
can't write to the output device that your user is monitoring (be it
stderr or some customised dialog routine or whatever). Some days, it
just isn't worth getting out of bed.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
May 17 '07 #9
In article <FP******************************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:
>"Warn the user" is the very least you can do for /any/ failure (except
one). Often you can do more, but even if you can't, at least you can
clue the user in to what is going wrong.

The one exception, of course, is where the failure is that your program
can't write to the output device that your user is monitoring (be it
stderr or some customised dialog routine or whatever). Some days, it
just isn't worth getting out of bed.
You could sit in a loop, so that the user has to kill the program.
That should make them think twice about checking the data is intact.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
May 17 '07 #10
William Ahern wrote:
Tor Rustad <torust_at_online.nowrote:
>empriser wrote:
>>FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.
fclose() returns 0 on success.

Even on failure fp is still effectively closed for all intents and purposes.
fp becomes (or remains) invalid either way.
fclose(NULL);

close nothing.

--
Tor <torust [at] online [dot] no>
May 17 '07 #11
On 17 May 2007 13:14:43 -0700, in comp.lang.c , "christian.bau"
<ch***********@cbau.wanadoo.co.ukwrote:
>On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
Depends why it failed. Could be tht the OS can't flush the buffers to
disk because there's no space at present, or it could be the
filehandle got corrupted, etc etc. Solutions would differ, and you'd
need to check other information to determine how to respond.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
May 17 '07 #12
christian.bau wrote:
On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
What type of program and system do you have in mind?

If we ignore trivial case of an invalid stream pointer on input,
typically a write to file failure has caused your fclose() error.

A very simplistic recovery, would be to retry the operation on the file,
but that is a gamble, possibly the file is already in a corrupted state
and further write to it, would only do more harm. On Linux EFBIG, it is
rather pointless to retry..

So, it depend on the error value set in errno, e.g. Linux EFAULT is bad,
your program is possibly in an undefined state, and the best thing to do
is usually exit ASAP.

Making programs fault tolerant is a complex topic, if I really don't
need that, I follow the "worse is better" design

http://www.jwz.org/doc/worse-is-better.html

and just log error to the system log and exit.
--
Tor <torust [at] online [dot] no>
May 17 '07 #13
On 17 May 2007 13:14:43 -0700, "christian.bau"
<ch***********@cbau.wanadoo.co.ukwrote:
>On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
>fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?
Notify the user, probably. Other than that, possible action depends on
why the call failed, and both the reasons and the error codes are
implementation dependent.

--
Al Balmer
Sun City, AZ
May 18 '07 #14
quarkLore <ag*************@gmail.comwrites:
On May 18, 1:14 am, "christian.bau" <christian....@cbau.wanadoo.co.uk>
wrote:
>On May 17, 12:11 pm, Richard Heathfield <r...@see.sig.invalidwrote:
fclose can fail. Check the return result. (Here, I'm speaking as much to
myself as to you!)

The question is: If it fails, what are you supposed to do? fclose can
obviously fail if I make some programming error, like fclose (fp);
fclose (fp); where the second call is quite likely to fail. But apart
from that, what can you do?

Error propagation and catching is a problem in C and in general
structured programming languages.
Coming back to the topic. You can check the errno.
Yes, but the C standard doesn't say that fclose() sets errno on
failure (though many implementations do so).

Set errno to 0 before the call, and check its value after the call
*only* if fclose() reported an error by returning EOF. (fclose()
returns 0 on success, EOF on error.)
Check this:
http://man.he.net/?topic=fclose&section=all

Check this to know how to use errno:
http://www.mkssoftware.com/docs/man5/errno.5.asp
http://www.unix.geek.org.uk/~arny/info/library_2.html
Based on a quick glance, that looks like good information, but some of
it is system-specific, and it doesn't mention the need to set errno to
0 before a call.

Consider a system where a given function *doesn't* set errno. Before
the call, it could have any arbitrary value from some previous error.
If the call fails without setting errno, you could end up using bogus
information.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
May 18 '07 #15
Tor Rustad <torust_at_online.nowrites:
William Ahern wrote:
>Tor Rustad <torust_at_online.nowrote:
>>empriser wrote:
FILE *fp;

fp = fopen( ... )
fclose( fp ).
How do I know if fp has been fclose.
fclose() returns 0 on success.
Even on failure fp is still effectively closed for all intents and
purposes.
fp becomes (or remains) invalid either way.

fclose(NULL);

close nothing.
I'm not sure what your point is, but fclose(NULL) invokes undefined
behavior. fclose "causes the stream pointed to by stream to be
flushed and the associated file to be closed"; if there is no such
stream, the behavior is undefined by omission.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
May 18 '07 #16
Keith Thompson wrote:
Tor Rustad <torust_at_online.nowrites:
>William Ahern wrote:
>>Tor Rustad <torust_at_online.nowrote:
empriser wrote:
FILE *fp;
>
fp = fopen( ... )
fclose( fp ).
>
>
How do I know if fp has been fclose.
fclose() returns 0 on success.
Even on failure fp is still effectively closed for all intents and
purposes.
fp becomes (or remains) invalid either way.
fclose(NULL);

close nothing.

I'm not sure what your point is, but fclose(NULL) invokes undefined
behavior. fclose "causes the stream pointed to by stream to be
flushed and the associated file to be closed"; if there is no such
stream, the behavior is undefined by omission.
I was puzzled by Tors post too. Some investigation reveals that the man
page for fclose() on Cygwin confirms this. Here's what it says:

`fclose' returns `0' if successful (including when FP is `NULL'
or not an open file); otherwise, it returns `EOF'.

So on such systems fclose(NULL) seems to be fine. Even
FILE *fp = fopen("whatever", "r");
fclose(fp);
fclose(fp);
fclose(fp);
should work on that implementation. A Very Bad Choice, IMO. Why not
stick to the standard?
Bjørn

--
Looking for an embeddable web server?
http://www.metasystems.no/products/h...der/index.html
May 18 '07 #17
"B. Augestad" <bo*@metasystems.nowrites:
[...]
I was puzzled by Tors post too. Some investigation reveals that the
man page for fclose() on Cygwin confirms this. Here's what it says:

`fclose' returns `0' if successful (including when FP is `NULL'
or not an open file); otherwise, it returns `EOF'.

So on such systems fclose(NULL) seems to be fine. Even
FILE *fp = fopen("whatever", "r");
fclose(fp);
fclose(fp);
fclose(fp);
should work on that implementation. A Very Bad Choice, IMO. Why not
stick to the standard?
I agree that it's a bad choice, but it does stick to the standard.
Returning 0 is perfectly consistent with undefined behavior.

Incidentally, it's not clear to me from the standard whether

FILE *fp = fopen("whatever", "r"); /* assume success */
fclose(fp);
fclose(fp);

invokes undefined behavior or not. C99 7.19.5.1 says that "the stream
is disassociated from the file", but it doesn't say that the stream no
longer exists after that.

I think one could argue that the second fclose() must succeed, or that
it must fail, or that it invokes undefined behavior. (Or maybe it's
just too early in the morning.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
May 18 '07 #18
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.orgwrote:
>Incidentally, it's not clear to me from the standard whether

FILE *fp = fopen("whatever", "r"); /* assume success */
fclose(fp);
fclose(fp);

invokes undefined behavior or not.
I'm not going to work through the standard right now, but this has to
be undefined behaviour. Otherwise FILE objects couldn't be re-used,
which they are in many implementations (and were even before C89).

Consider:

FILE *fp1 = fopen("whatever1", "r"); /* assume success */
fclose(fp1);
FILE *fp2 = fopen("whatever2", "r"); /* assume success */

In many implementations fp1 and fp2 are equal (yes, in theory it's
probably undefined behaviour to compare them). Calling fclose(fp1)
again at the end will close the second file.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
May 18 '07 #19
Keith Thompson wrote:
I'm not sure what your point is, but fclose(NULL) invokes undefined
behavior.

Agreed, fclose(NULL) is UB.

--
Tor <torust [at] online [dot] no>
May 18 '07 #20

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

Similar topics

22
by: Bryan | last post by:
i'm curious to know how others handle the closing of files. i seem to always end up with this pattern even though i rarely see others do it. f1 = file('file1') try: # process f1 finally:...
8
by: Peter Abel | last post by:
Hi all, I'm working under W2k with Python 2.2.2 (#37, Oct 14 2002, 17:02:34) on win32 I have a file *test_data.txt* with the following content: 0123456789 0123456789 abcdefghi...
3
by: Pernell Williams | last post by:
Hi all: I am new to Python, and this is my first post (and it won't be my last!), so HELLO EVERYONE!! I am attempting to use "xreadlines", an outer loop and an inner loop in conjunction with...
0
by: Prabhu Ramachandran | last post by:
Hi, I noticed peculiar behavior under Python-2.3.4 under Win32. When I run something like this: f = open('t.txt', 'wb') f.write('1\012'+'2\012'+'3\012') f.close() f = open('t.txt', 'r')...
3
by: DJTN | last post by:
I have created 2 vb.net applications in VS 2002, a server and a client using the .net.sockets namespace. I can connect and receive data fine but the client cannot tell when it has recived all the...
1
by: Steve | last post by:
is there a way to tell how a form has been changed? I want a button that will close the form and undo anything if detected to avoid having two buttons, one for undo and then one for close. ...
0
by: Andrew Dowding | last post by:
Hi Everybody, I have been looking at problems with my Windows Forms C# application and it's little Jet 4 (Access) database for the last few days. The Windows Forms app implements a facade and...
4
by: Vlad | last post by:
I am having problems using the file.create method within a function that is called when looping through an array of filepaths. If I call my function with a hardcoded file path --C:\Temp.txt the...
5
by: Metalone | last post by:
In particular I want to know how to tell if reading and writing to the console can occur. Something like sys.isConsolePresent()
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: 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
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.