473,785 Members | 2,841 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fclose... what is better

hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);

thanks

Nov 14 '05 #1
10 2017
In article <11************ **********@z14g 2000cwz.googleg roups.com>,
collinm <co*****@laboit eaprog.com> wrote:
is it better to do:
or FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);


What is the defined behaviour of fclose(NULL) ?

If you don't know off the top of your head, chances are that
other people maintaining your program will not either. Thus,
regardless of the defined behaviour of fclose(NULL), your
program would be more maintenance-friendly if you do not
invoke that behaviour.
By the way, as a minor matter of style: messages such as "fail"
are most often associated with errors rather than with normal
program behaviour. Messages associated with errors are usually
sent to stderr instead of stdout.

If the unavailability of the file is a routine matter for the program,
then the associated message would usually not be "fail" but instead
something closer to "skipping unavailable file %s\n" or "Sorry, no
winking blinking lights available today!\n"
--
Studies show that the average reader ignores 106% of all statistics
they see in .signatures.
Nov 14 '05 #2
collinm wrote:
hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);

thanks


All depends on your style and error handling.
My preference is:
unsigned char successful = 0;
fp = fopen(...);
successful = fp == NULL;
if (!successful)
{
/* File open failure */
}

if (successful)
{
successful = Process_File_Co ntents();
}

if (successful)
{
/* ... */
}

As for when to close a file, my opinion is to
close it as soon as you are finished with it.
Leaving a file open for longer than necessary
may allow things to happen to the internal data
{by your program or other ones).

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
Nov 14 '05 #3


collinm wrote:

hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );

or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);
Do not call fclose(fp) if fp is NULL.

thanks


--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Common User Interface Services
M/S 2R-94 (206)544-5225
Nov 14 '05 #4


collinm wrote:
hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);


"Better" depends on what you want to accomplish, of
course. However, note that if the fopen() fails in the
second version you will wind up calling fclose(NULL),
which is Not A Good Idea ...

--
Er*********@sun .com

Nov 14 '05 #5

"collinm" <co*****@laboit eaprog.com> wrote in message
is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);

As others ahve pointed out, you don't want to call fclose() on a null
pointer.

The fopen() expression is not a disaster, but makes it look as if the
purpose of the call is to check a condition, whilst in fact the purpose is
to assign a file pointer to fp.

So

FILE *fp;

fp = fopen(local_led , "r");
if(fp)
{
/* manipulate the file */
fclose(fp);
}
else
printf("fail\n" );

is the style that I use.
Nov 14 '05 #6
collinm wrote:
hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);

thanks


I think the general recommendation is to deal with exceptions first:

FILE *fp;

fp = fopen(local_led , "r");
if(fp == NULL) {
fprintf(stderr, "Could not open the file %s", local_red);
exit(EXIT_FAILU RE);
}
....
fclose(fp);

-- August
Nov 14 '05 #7
"August Karlstrom" <fu********@com hem.se> wrote in message
news:qX******** *************@n ewsc.telia.net. ..
collinm wrote:
hi

is it better to do:

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
fclose(fp);
}
else
printf("fail\n" );
or

FILE *fp;
if((fp = fopen(local_led , "r"))!=NULL )
{
printf("oepn\n" );
}
else
printf("fail\n" );
fclose(fp);

thanks


I think the general recommendation is to deal with exceptions first:

FILE *fp;

fp = fopen(local_led , "r");
if(fp == NULL) {
fprintf(stderr, "Could not open the file %s", local_red);
exit(EXIT_FAILU RE);
}
...
fclose(fp);

-- August


'THE' general recommendation? BS.
What happens when you can't exit() because of your requirements?
Do you replace the call with a return? I've fixed more problems caused
by sloppy coding conventions similar to this one you 'recommend'...
especially when multiple files are being opened and manipulated at once.
My personal recommendation would be to code an fopen() as follows:

FILE *fp;
if((fp = fopen(local_led , "r"))) {

fclose(fp);
} else
perror(local_le d);

Mark
Nov 14 '05 #8
Mark wrote:
"August Karlstrom" <fu********@com hem.se> wrote in message
I think the general recommendation is to deal with exceptions first:

FILE *fp;

fp = fopen(local_led , "r");
if(fp == NULL) {
fprintf(stderr, "Could not open the file %s", local_red);
exit(EXIT_FAILU RE);
}
...
fclose(fp);

-- August

'THE' general recommendation? BS.
What happens when you can't exit() because of your requirements?
Do you replace the call with a return? I've fixed more problems caused
by sloppy coding conventions similar to this one you 'recommend'...
especially when multiple files are being opened and manipulated at once.
My personal recommendation would be to code an fopen() as follows:

FILE *fp;
if((fp = fopen(local_led , "r"))) {

fclose(fp);
} else
perror(local_le d);

Mark


Okay, my point was really the order of the branches:

FILE *fp;

fp = fopen(local_led , "r");
if(fp == NULL) {
/* Do whatever has to be done when local_red cannot be opened. */
} else {
...
fclose(fp);
}

Of course, what you have do when `fopen' fails depends on how the
program is structured; preconditions, postconditions etc. (My previous
example didn't need the else clause because of the invokation of `exit'.)

-- August
Nov 14 '05 #9
On Thu, 19 May 2005 13:56:37 GMT, Thomas Matthews
<Th************ *************@s bcglobal.net> wrote:
<snip>
All depends on your style and error handling.
My preference is:
unsigned char successful = 0;
fp = fopen(...);
successful = fp == NULL;
Shirley <G> you mean fp != NULL .
if (!successful)
{
/* File open failure */
}

if (successful)
{
successful = Process_File_Co ntents();
You should pass fp, otherwise it needs to be a shared "global" (at
least file-scope static, maybe more) which is yucky(tm) far beyond
this mildly clunky error handling.

Presumably the fclose() is done within Process_File_Co ntents(), in
which case the name is not fully descriptive, or added here ...
}
because now 'successful' no longer tells you accurately whether the
fopen was successful -- although fp does, it you are willing to
violate the structuring you just put so much effort into.
if (successful)
{
/* ... */
}

As for when to close a file, my opinion is to
close it as soon as you are finished with it.
Leaving a file open for longer than necessary
may allow things to happen to the internal data
{by your program or other ones).


Promptly closing a file (not opened read-only enforced by the OS) can
protect it from malfunctions in other parts of the same program --
although it would be better to fix those malfunctions anyway -- but is
very unlikely to help protect against other _programs_; indeed it may
release locks and allow _more_ access to the file by other programs.

- David.Thompson1 at worldnet.att.ne t
Nov 14 '05 #10

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

Similar topics

3
6579
by: VB | last post by:
Hi, here File.cpp and File.h: File.cpp: ---------------------- #pragma warning (disable: 4786)
11
6421
by: Marcus Jacobs | last post by:
Dear Group I have encountered a problem with fclose and I am wondering if anyone could provide some insight about this problem to me. Currently, I am working on a small personal project that is requiring for me to alter some existing code to a program. While running the unaltered code, I kept encountering an application (The exception unknown software exception(0xc00000fd) etc. .. etc... etc... I am running W2K Pro). Through a bit of...
19
6810
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 what happens in memory operations, everyone knows the importance of freeing the allocated memory, but there do have memory leaks from time to
17
14788
by: kathy | last post by:
if fopen failed, does it necessary to call fclose? I see an example like this: .... stream = fopen(...); if(stream == NULL) { .... } else
20
7308
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 stream so that the tape driver will write a filemark on the tape. Otherwise multiple clumps of data saved to tape would all appear to be one big file on the tape. When the tape unit device was explicitly opened with fopen() that's possible:...
53
4483
by: Bartc | last post by:
This short program: #include <stdio.h> #include <stdlib.h> int main(void) { int status; status=fclose(0);
16
2602
by: Bill Cunningham | last post by:
Is it really necessary to check the return type (int) or fclose ? fopen I can understand but what about using fflsuh(fp); /* fopen's pointer */ fclose(fp); Would that take care of any unforseen truncation ? Bill
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10330
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10153
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9952
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3654
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.