null FILE* pointers

K

kelvSYC

With std::fopen, will it return a null pointer if the file does not
exist? If so, how do I make it so that it will attempt to create a
file if it doesn't exist? Would moving to fstreams/filebufs address
these issues?
 
A

Alipha

The documentation (eg,
http://www.die.net/doc/linux/man/man3/fopen.3.html ) says that if you
open the file for write or append (in addition to read if you'd like)
the file will be created if it doesn't exist.

And std::fstream would be preferred in c++ anyway. stream
insertion/extraction operators (<< and >>) are safer and more
extendable and such than printf/scanf style functions.
 
D

Default User

kelvSYC said:
With std::fopen, will it return a null pointer if the file does not
exist?

It depends on the mode argument to fopen().
If so, how do I make it so that it will attempt to create a
file if it doesn't exist?

That depends on the mode argument to fopen(). Did you read up on that?
Your documentation should explain.




Brian
 
D

Default User

Default said:
It depends on the mode argument to fopen().

It may also depend on platform-specific things, such as file
permissions. That is, a file may exist but the application not have
permission to open it. That's why the trick of trying to open a file
for reading is not always an adequate test for file existence.



Brian
 
C

Christopher Benson-Manica

(Assuming std::fopen behaves more or less like fopen() from C:)
With std::fopen, will it return a null pointer if the file does not
exist?

fopen returns a null pointer if the attempt to open the file fails.
This can happen for various reasons; one of which, of course, is that
the file does not exist. However, if the mode is "w" or "a", the file
will be created if it does not exist; if you get a null pointer in one
of these modes, something else has presumably gone wrong.
If so, how do I make it so that it will attempt to create a
file if it doesn't exist?

If you're opening for read, you can use "a+" as the mode; this will
open the file for read and write and create the file if it does not
exist.
Would moving to fstreams/filebufs address
these issues?

Probably, but I'll leave the answer to knowledgeable types.
 

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

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top