Question about freopen() failure

K

Kenneth Brody

What happens to the existing file stream if freopen() fails? For
example:

FILE *f = freopen("/a/filename/that/fails/to/open","w",stdout);

If the specified filename fails to open, is stdout now closed? From
my reading, it appears so:

7.19.5.4p4:

The freopen function first attempts to close any file that is
associated with the specified stream. Failure to close the file
is ignored.

In other words, the current stream is closed, and only then does it
attempt to open the specified file.

Am I correct that an freopen() on stdout that fails leaves the program
without any stdout, and that a future fopen() could end up giving that
file to stdout?

(A test program on a particular platform confirms that, on that
platform at least, this does occur.)

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:[email protected]>
 
E

Eric Sosman

Kenneth said:
What happens to the existing file stream if freopen() fails? For
example:

FILE *f = freopen("/a/filename/that/fails/to/open","w",stdout);

If the specified filename fails to open, is stdout now closed? From
my reading, it appears so:

7.19.5.4p4:

The freopen function first attempts to close any file that is
associated with the specified stream. Failure to close the file
is ignored.

It seems to me that stdout "is closed" after the failed
freopen(), but that the original stream may or may not have
been "properly closed" -- for example, it may or may not
have been fflush()ed. It would certainly be a bad idea to
try to use stdout after the failure ...

You might want to try this question on comp.std.c.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

freopen() 3
manipulate fd underlying stream 38
Question about my projects 3
realloc() to zero size 5
Pointer arithmetic question 23
Sorta-OT: John Backus obit 5
"(unsigned)" with long/int 10
YKYBRclcTLW 13

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top