473,815 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to write this?

Hi all,
I am new to C programming,
All I just need to know is how to write the
following in C,
if (open STDOUT){
close the STDOUT
}

Can anyone guide me
Thanks

Nov 15 '05
15 1355
On Thu, 08 Sep 2005 10:18:21 +0000, Richard Tobin wrote:
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
And given a sequence like this:

fclose(foo);
bar = fopen("whatever ");
fclose(foo);

it's possible (I think) that bar could point to a FILE object at the
same address as the one released by the first fclose(). The second
fclose() would then close bar.
The description of freopen() says that it "attempts to close any file that
is associated with the specified stream". The use of "any" suggests that
the stream may already have been closed - compare fclose() which talks
about "the" file.


When a stream is closed it ceases to be a stream, like when a malloc()'d
object is freed it ceases to be an object.

freopen() requires that you pass it a pointer to valid stream; a stream
that has been closed doesn't meet that requirement and you get undefined
behaviour. The same is true for all functions that take a FILE * argument,
except that you can pass a null pointer to those that say explicitly that
you can (fflush). In particular passing a pointer to anything that a
proper open stream to fclose() invokes undefined behaviour.

Lawrence


closed isn't a stream
any more (loke an object that has been freed isn't an object any more).

-- Richard


Nov 15 '05 #11
Keith Thompson wrote:
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <pa************ *************** *@gmail.com>,
Robert Gamble <rg*******@gmai l.com> wrote:
On Wed, 07 Sep 2005 13:44:29 -0400, Kenneth Brody wrote:

So, the following is well-defined, assuming you pass a valid FILE*?

int my_fclose(FILE *f)
{
fclose(f);
return(fclose(f ));
}

Nope, the value of f is indeterminate after the first fclose, the second
fclose invokes undefined behavior.


The value of f cannot change as a result of fclose, as it is passed
by value. What f points -to- might change, of course.

The C standard says that FEOF is returned if an error is encountered,
and places no constraints about what kind of error that might be.

If one drops over to POSIX.1 then fclose() is defined in terms of
close() and write(), and close() is defined with a specific errno
if the descriptor is not open; so for POSIX.1 at least, fclose() of
something already closed is defined.


The C standard says:

A successful call to 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. Whether or not the call succeeds, the
stream is disassociated from the file and any buffer set by the
setbuf or setvbuf function is disassociated from the stream (and
deallocated if it was automatically allocated).

It looks like the effect of fclose() on a file that's already been
closed isn't specified, which makes it undefined behavior.

And given a sequence like this:

fclose(foo);
bar = fopen("whatever ");
fclose(foo);

it's possible (I think) that bar could point to a FILE object at the
same address as the one released by the first fclose(). The second
fclose() would then close bar.


Or it might not, in which case when it deallocates any buffer it might
call free on a pointer that has already been freed thus causing anything
to happen and a good (IMHO) example of why the C standard leaves it
undefined.

POSIX is, of course, allowed to define what happens on POSIX systems
when you invoke some specific case that C leaves undefined, but as far
as C is concerned it is still undefined.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #12
On Thu, 08 Sep 2005 03:38:35 +0000, Walter Roberson wrote:
In article <pa************ *************** *@gmail.com>,
Robert Gamble <rg*******@gmai l.com> wrote:
On Wed, 07 Sep 2005 13:44:29 -0400, Kenneth Brody wrote:
So, the following is well-defined, assuming you pass a valid FILE*? int my_fclose(FILE *f)
{
fclose(f);
return(fclose(f ));
}

Nope, the value of f is indeterminate after the first fclose, the second
fclose invokes undefined behavior.


The value of f cannot change as a result of fclose, as it is passed
by value. What f points -to- might change, of course.


That is of course what I meant, thanks for the correction.
The C standard says that FEOF is returned if an error is encountered,
That's EOF, not FEOF.
and places no constraints about what kind of error that might be.
But it mandates that even in failure, the function disassociates the
stream from the file. If you are saying that the first fclose could fail
and the second one could succeed without invoking undefined behavior then
I'll have to disagree for now (the wording in the standard regarding
this is a little sticky, it may be possible to persuade me otherwise).
If one drops over to POSIX.1 then fclose() is defined in terms of
close() and write(), and close() is defined with a specific errno
if the descriptor is not open; so for POSIX.1 at least, fclose() of
something already closed is defined.


Your logic is flawed, just because fclose performs a close (actually, the
"equivalent " of close() according to the standard), that doesn't mean that
is all it does. It could very well free other resources associated with
the stream for example. In any case, POSIX.1 states "After the call to
fclose(), any use of stream results in undefined behavior". I hope
you'll agree that calling fclose on a stream qualifies as a use of
that stream. This appears to include the case where fclose fails.

Robert Gamble
Nov 15 '05 #13
In article <pa************ ***********@net active.co.uk>,
Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
The description of freopen() says that it "attempts to close any file that
is associated with the specified stream". The use of "any" suggests that
the stream may already have been closed - compare fclose() which talks
about "the" file.
When a stream is closed it ceases to be a stream, like when a malloc()'d
object is freed it ceases to be an object.


A good theory, but it doesn't explain why freopen() says "any" instead
of "the".

-- Richard
Nov 15 '05 #14

In article <df**********@c anopus.cc.umani toba.ca>, ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <pa************ *************** *@gmail.com>,
Robert Gamble <rg*******@gmai l.com> wrote:
Nope, the value of f is indeterminate after the first fclose, the second
fclose invokes undefined behavior.
The value of f cannot change as a result of fclose, as it is passed
by value. What f points -to- might change, of course.


I believe the same principles apply here as with free():

The representation of the value of f cannot change (maybe; I'm not
sure anyone ever definitively established that for free), but the
interpretation of that value can. For example, if the implemen-
tation of fopen returns a malloc'd pointer, and fclose frees that
pointer, then any reference to the value of f after a successful
fclose invokes undefined behavior.
If one drops over to POSIX.1 then fclose() is defined in terms of
close() and write(), and close() is defined with a specific errno
if the descriptor is not open; so for POSIX.1 at least, fclose() of
something already closed is defined.


Not if fclose() frees the FILE*. The fclose implementation may
never reach the call to close().

--
Michael Wojcik mi************@ microfocus.com

The guy who's fast in the mountain pass is the coolest.
-- _Initial D: Second Stage_
Nov 15 '05 #15
On Wed, 7 Sep 2005 17:21:14 +0000 (UTC), ro******@ibd.nr c-cnrc.gc.ca
(Walter Roberson) wrote:
<snip>
There is no specific call in C to determine whether a particular
FILE* is open: you just try an operation on it and check to see
if the operation failed with a code indicating the file is closed.
Or for your purposes, as one of the posters pointed out, just
go ahead and close it: you won't bomb if it is already closed.
As others have already said, there is no such guarantee in C; the
memory to which a FILE * points can be deallocated on fclose() and any
use of it (or formally even of the pointer) is undefined and can fail.

<OT> Even in SUS2 and 3, which are what I have to hand, [EBADF]
says "The file descriptor underlying stream is not valid." Note,
nothing about the _stream_ not being valid.

In SUS/POSIX, if you only close() the underlying fd but _not_ fclose()
the stdio stream, then at least operations that actually try to use
the underlying file seem guaranteed to reject with EBADF. </>

STDOUT on the other hand is not a FILE*; it is generally part of
an I/O extension in which STDOUT is a macro which evaluates to the
"underlying descriptor" number of C's FILE* stdout . File descriptor
numbers are not part of C itself; many operations with file descriptors
are formalized in POSIX.1 . The typical operation to close a
file associated with a file descriptor is close(). There is no
standardized specific call to find out whether a file descriptor is
open, but you can fstat() the descriptor and look to see whether
you received the error that indicates the descriptor is not open.


Or fcntl(,F_GETFL) . Or lseek(,0,SEEK_C UR). The "low-level" I/O
operations are guaranteed to fail cleanly, no undefined behavior.

Note however that file descriptors can be and almost always are
reused. (Stdio FILE *'s also _can_ be reused, but only sometimes are.)
If you have a stale fd-number and test it before doing I/O, it may
have been reused by an open() (or socket() etc.) elsewhere in the
program, so your test mistakenly thinks it is "still open" but your
I/O does something almost certainly wrong. There is no adequate
alternative to remembering for yourself which files you have open.

- David.Thompson1 at worldnet.att.ne t
Nov 15 '05 #16

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

Similar topics

6
16620
by: Tony C | last post by:
Does Python have a function that is analogous to C's write() or fwrite()- that is , I want to write a file (of arbitrary data) that is 100K, or 1MB (or more) bytes long.. Both write() and fwrite() in C allow the user to specify the size of the data to be written. Python's write only allows a string to be passed in.
33
3500
by: Nick Evans | last post by:
Hello there, I have been on and off learning to code (with python being the second language I have worked on after a bit of BASIC). What I really want to know is, if you are going to actually write a program or a project of some sort, how do you actually start. Picture this, you know what you want the program to do (its features), you have a possably rough idea of how the program will work. You have opened an empty text file and saved...
10
2912
by: Greg Hurlman | last post by:
I've got what I'm sure is a very simple problem. In an ASP page, I am trying to write out 4 fields from a recordset in succession: Response.Write rs("LastName") Response.Write rs("Suffix") Response.Write rs("FirstName") Response.Write rs("MiddleInitial") All fields are populated and are single terms. I would expect "LastNameSuffixFirstNameMiddleInitial" ("UserIIITestA" in my test record) to
1
2875
by: techy techno | last post by:
Hii Just wanted to know how can I decorate my texboxes and Listmenu which is called from a JS file using the following code below: document.write("<SELECT NAME='cur2' ONCHANGE='cconv1();'>"); document.write("<OPTION VALUE='0.345066110642241'>Argentina Peso </OPTION>"); document.write("<OPTION VALUE='0.790200069503053'>Australia Dollar
3
2525
by: Ike | last post by:
Can anyone discern why the following code writes the document.write() lines literally? That is, a line like document.write('<CENTER>') should write <CENTER> but instead writes the entire document.write('<CENTER>'). I must be really doing something stupid. Can anyone here illuminate me? Thanks, Ike <HTML><HEAD> <TITLE>My Applet</TITLE> </HEAD><BODY>
2
2389
by: Brett Baisley | last post by:
Hello I have a block of html code that I want to run by calling a javascript function to print it. Its basically a table with menu items in it that is the same for many pages, and instead of copying/pasting everytime I change it, I figure this will be better, as I only change it once. The problem is, document.write doesn't handle multiple lines very well, so I was wondering what is the best way to do this? Maybe there is even a better...
0
1766
by: hari krishna | last post by:
hi all, My requirement is to generate xl reports throu Asp.Net without installing xl on web server computer. i am using Response object and wrtifile method as below. i dont know whether it is correct, but giving error says " file is accessed by other process cannot access" I have some logic inbetween and write the info using response.write in to html format Ex: Response.Write("<td>" & "client_no" & "</td>"). I am getting the error at :...
3
3898
by: Brett_A | last post by:
I'm trying to write data from a form using a text box (textarea) that has a return after each item. For example: email1@domain.com email2@domain.com email3@domain.com email4@domain.com I'm getting the data written to the SQL server table fine, but every item after the first is getting written with a special character
1
7548
by: anupamaavadutha | last post by:
hi all, iam new to javascript. i have problem calling javascript functions.iam designing a calender page.here is my code. <%@ page import='java.io.*,java.util.*,java.sql.*,javax.servlet.*,javax.servlet.http.*' session='true'%> <%@ page import='java.text.*'%> <html> <script language='javascript'> function backward() { alert("hello"); }
8
7114
by: Mateusz Viste | last post by:
Hi, I am trying make some multimedia files playable from my website. So far, I am able to generate dynamically a new page containing the right <embed> section. However, when I load my script, it overwrites the current page. Is there any way I could load a new tab or window, and put the new content into it? Here is the script I am using right now:
0
9735
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
10672
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...
1
10427
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10143
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...
0
9225
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6897
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
5570
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...
1
4358
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3030
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.