-1

If I open a (say) binary file, and I want to append the end of it both of the following ways seem to work for me

fileVar = fopen("FileName", "w+b");

and

fileVar = fopen("FileName", "r+b");

I have read the documentation, but I'm not clear about the difference between these two methods of opening the file. This website says that w+ will overwrite a file if it doesn't exist already, and a+ will append to the end of the file. I haven't tried using a+, but it seems to do the same thing as r+.

Question: What exactly is the difference between the three ways of opening a file, r+, w+ and a+?

Kitchi
  • 1,874
  • 4
  • 28
  • 46

2 Answers2

6

r+ starts at beginning of file, but will not create a new file if it doesn't exists.

w+ truncates existing file to zero length if the file exists, otherwise creates a new file.

a+ starts at end of file if file exists, otherwise creates a new file.

Access modes r+, w+ and a+ opens the file in read and write mode, but with the above difference:

Both r+ and w+ we can read ,write on file but r+ does not truncate (delete) the content of file as well it doesn’t create a new file if such file doesn’t exits while in w+ truncate the content of file as well as create a new file if such file doesn’t exists.

Butani Vijay
  • 4,181
  • 2
  • 29
  • 61
0

Just like the website says:

  • r+ will open the file for reading & writing, but the file must exist.
  • w+ will open the file for reading & writing, but if the file exists it will truncate the file (remove its contents).
  • a+ will open the file for reading & writing, but while reading is allowed at any location, you can only write to the end of the file, i.e. append.
Kninnug
  • 7,992
  • 1
  • 30
  • 42