What is the difference between a and a+ option in fopen function?

c++ c
23,832

Solution 1

Here is what the man pages (man fopen) say:

a

Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.

a+

Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.


Which means:

for a+: pointer initially is at the start of the file ( for reading ) but when a write operation is attempted it is moved to the end of the file.

Solution 2

Yes, there is an important difference:

a: append data in a file, it can update the file writing some data at the end;

a+ : append data in a file and update it, which means it can write at the end and also is able to read the file.

In a pratical situation of only writing a log both are suitable, but if you also need to read something in the file (using the already opened file in append mode) you need to use "a+".

Share:
23,832
domlao
Author by

domlao

Updated on December 17, 2021

Comments

  • domlao
    domlao over 2 years

    I can't understand the description of the "a" and "a+" option in the C fopen api documentation. The option in "a+" is append and update. What is the meaning of the word update here?

  • Mark Adler
    Mark Adler almost 10 years
    Don't get all uppity about it -- not all man pages are the same. Mine says: a Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar. and a+ Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.
  • Mark Adler
    Mark Adler almost 10 years
    A quick test shows that the first read on a non-empty file (before any writes) returns EOF. So in this case it reads from the end. This is on Mac OS X.
  • M.M
    M.M almost 4 years
    in Standard C for a+ it is implementation-defined whether the read pointer starts at the beginning or the end. The man page gives the behaviour for some specific system. Also , in Standard C, you must always seek between reading and writing