Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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?

like image 255
domlao Avatar asked Nov 09 '13 09:11

domlao


People also ask

What is the difference between A and A+ mode?

a - opens a file in append mode. r+ - opens a file in both read and write mode. a+ - opens a file in both read and write mode.

What is difference between R+ and A?

7. Difference between r+ and a+ in open() If the file does not exist, r+ throws FileNotFoundError ; the a+ creates the file. For r+ mode, the initial file pointer position at the beginning of the file ; For a+ mode, the initial file pointer position at the end of the file .


2 Answers

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.

like image 67
sukhvir Avatar answered Oct 22 '22 10:10

sukhvir


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+".

like image 21
Cleber Jorge Amaral Avatar answered Oct 22 '22 12:10

Cleber Jorge Amaral