Post by Philipp Klaus Krause
Does C support the opening of a file for both reading and writing, such
that an empty file is created when the file does not yet exist?
These are the modes defined by the C standard (188.8.131.52p3):> r open
text file for reading
Post by Philipp Klaus Krause
w truncate to zero length or create text file for writing
wx create text file for writing
a append; open or create text file for writing at end-of-file
rb open binary file for reading
wb truncate to zero length or create binary file for writing
wbx create binary file for writing
ab append; open or create binary file for writing at end-of-file
r+ open text file for update (reading and writing)
w+ truncate to zero length or create text file for update
w+x create text file for update
a+ append; open or create text file for update, writing at end-of-file
r+b or rb+ open binary file for update (reading and writing)
w+b or wb+ truncate to zero length or create binary file for update
w+bx or wb+x create binary file for update
a+b or ab+ append; open or create binary file for update, writing at end-of-file
Is is OK if the only things you can read are things written to the file
after it is opened? If so, w+ or w+b would do the job, depending upon
whether you want text mode or binary mode. Both modes truncate an
existing file to length 0, so you would not be able to read anything
that was in the file before it was opened.
Is it OK if the only place you can write is at the end of the file? Then
you can use either a+ and a+b.
However, if you want the ability to read things that were already in the
file before you opened it, and the ability to write to arbitrary
locations, and the creation of a new empty file if the file does not
already exist, you can't do that with a single call to fopen(). You'll
have to first attempt to open an existing file using either r+ or r+b.
If that attempt fails, it might be because the file does not exist, or
it might be because of other reasons (such as having insufficient
permissions). There's no portable way to distinguish those
possibilities, though in practice perror() will often be useful for that
purpose, but the standard does not require that. If that attempt fails,
then try to open it using w+x or w+b.
There are special rules to be followed when opening a file in update
mode (any mode containing a '+'):
"... both input and output may be performed on the associated stream.
However, output shall not be directly followed by input without an
intervening call to the fflush function or to a file positioning
function (fseek, fsetpos, or rewind), and input shall not be directly
followed by output without an intervening call to a file positioning
function, unless the input operation encounters end- of-file. Opening
(or creating) a text file with update mode may instead open (or create)
a binary stream in some implementations." (184.108.40.206p7)